OK. So I have been googling a lot, also this forums, but I still do not have answer for a presumably easy question.
How to reliably get
current CPU usage by a process.
I do not mean
ps command below - because it returns an average CPU usage in whole process lifetime. I need a snapshot of current usage.
Code:
ps -C processname -o %cpu=
The only solution I came up with is this:
Code:
top -n 1 | grep processname | awk '{print $10}'
But it is not reliable, because top command returns a number of rows limited to the screen hight and sorts by cpu usage decreasingly - so if a process uses 0% of CPU, it is on the end of the top listing and does not show on the list. Therefore in such situation this command returns empty string.
The code above would work if I could sort top's command listing by pid or start time. Is it possible? If it is not possible, how to reliably get current CPU usage of a process?
-----------------------------------------------------------------------
P.S. Showing the bigger picture, the point is to make this bash script work:
Code:
#!/bin/bash
cpuLoad=$(top -n 1 | grep processname | awk '{print $10}')
if [ $(echo $cpuLoad) -lt 40 ]
then echo CPU USAGE IS LOW
fi
This script does not work well, because if cpuLoad variable returns empty string then an error shows up:
./test: line 3: [: -lt: unary operator expected
I can detect the situation where empty string instead of CPU load is returned with such code:
Code:
if [ ! -n "$cpuLoad" ]
but I do not have a clue how to write a code with combined conditions that will work like this:
IF cpuLoad is empty
OR cpuLoad < 40 THEN...
The problem with such statement is that upon attempt to evaluate second condition an error will show up because the cpuLoad variable is empty, while value is expected.