You are not logged in.
I'm writing a bash script to log some selection from a sensors output (core temp, mb temp, etc.) and I would also like to have the current cpu usage as a percentage. I have no idea how to go about getting it in a form that a bash script can use. For example, I would simply look in the output of htop, but again, I need to assign the % load to a variable in a bash script.
Does anyone know how I can do it?
CPU-optimized Linux-ck packages @ Repo-ck • AUR packages • Zsh and other configs
Offline
'vmstat | cut -c 72-74 > log' will get you the cpu_idle%. Do you mean sth like that? it may work, but what about 100% (3 digits instead of 2)?
Offline
It looks like vmstat is a total since the beginning, not of the last x minutes or something useful.
You need to run a program that monitors the time stats in /proc/stat, and logs the difference since the last iteration (this is what e.g. htop does) in a file, which you can then open when you need it in your script. Otherwise the script would have to be running for at least "some" interval.
Continuous script: (output it to a file and get the last results with tail -n 1)
while true; do eval $(awk '/^cpu /{print "idle=" $5 "; total=" $2+$3+$4+$5 }' /proc/stat); intervaltotal=$((total-${prevtotal:-0})); echo "$((100*( (intervaltotal) - ($idle-${previdle:-0}) ) / (intervaltotal) ))"; previdle=$idle; prevtotal=$total; sleep 5; done
Slow single percentage:
eval $(awk '/^cpu /{print "previdle=" $5 "; prevtotal=" $2+$3+$4+$5 }' /proc/stat); sleep 0.4; eval $(awk '/^cpu /{print "idle=" $5 "; total=" $2+$3+$4+$5 }' /proc/stat); intervaltotal=$((total-${prevtotal:-0})); echo "$((100*( (intervaltotal) - ($idle-${previdle:-0}) ) / (intervaltotal) ))"
Try to make sleep 0.4 as high as possible, at least.
Last edited by Procyon (2009-11-24 23:41:59)
Offline
Very nice Procyon.
Setting Up a Scripting Environment | Proud donor to wikipedia - link
Offline
I'll give this a try. Thanks!
CPU-optimized Linux-ck packages @ Repo-ck • AUR packages • Zsh and other configs
Offline