Question

I need to put the CPU value of a particular pid into a variable to detect its value.

I am able to get the pid of the program by using pidof and I am able to get the CPU value by using:

ps -p <pid> -o %cpu

which gives me:

%CPU
14.8

But I do no want the %CPU part, just the value, to then put into a variable to then question whether it is above 90% or not.

Could you please offer any assistance?

Thank you.

Was it helpful?

Solution

Rename the header using ps' -o field=name syntax with an empty name:

cpu_percent=$(ps -p "$yourpid" -o %cpu=)

To test whether it's greater than some value, we can strip the decimals (bash can't handle them) and compare:

yourpid=$$  # Example using current shell's pid

cpu_percent=$(ps -p "$yourpid" -o %cpu=)
echo "Fractional percent is $cpu_percent"

cpu_percent=${cpu_percent%%.*}
echo "Integer percent is $cpu_percent"

if [ "$cpu_percent" -ge 40 ]
then
  echo "It's more than 40"
fi

OTHER TIPS

Use tail to print the last line

ps -p <pid> -o %cpu | tail -n 1

If you want it in a variable, do this:

percent=$(ps -p <pid> -o %cpu | tail -n 1)

The $() syntax means "put the result of running the command inside the parentheses into a variable".

Then you can compare like this:

# Convert to integer
percent=${percent/.*/}
if [ $percent -gt 20 ]; then
   echo Greater
else
   echo Less
fi

To get ps not to print the header material (%CPU, in your case):

ps h -p <pid> -o %cpu

h option turns off headers

man ps for more info

This way, you don't have to use tail -n 1 as above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top