Shell script - getting cpu usage (%cpu) and storing it into a variable

Viewed 1113

I am trying to retrieve the cpu usage (%cpu) of a process and store it into a variable. I am able to display the %cpu and the command using Shell script:

echo Enter the process name you wish to fetch:
read pn
#Displays %cpu of process
ps -eo %cpu,command | grep $pn

Output:

Enter the process name you wish to fetch:
terminal
0.0 grep terminal

'0.0' defines the %cpu and 'grep terminal' defines the command (process).

How can I put the value of the cpu usage (%cpu) into a variable as such:

declare -x cpuUsage=[%cpu of process]
echo $cpuUsage
1 Answers

You need something like this to store the usage value in a variable:

echo Enter the process name you wish to fetch:
read pn
cpuusage=`ps -eo %cpu,command | grep $pn | grep -v grep | head -n 1 | sed 's,^ *,,' | cut -d ' ' -f 1`
echo $cpuusage

Be aware that if many processes matches the given name it simply takes the first returned by the ps output.

Related