Let's assume that column 9 in the output of the top
command is a good measure of the CPU usage. I don't really know, but let's assume.
Your script could be written cleaner and better:
- Don't use
`...`
style process substitution, use $(...)
instead
- Usually, there's no point piping the output of one
awk
command to another. You can do what you did in a single awk
, which is better, because you save one unnecessary process
- Better to pass variables to
awk
using the -v
parameter than trying to embed in the command line
- Don't use
printf
when an echo
is enough and simpler
- Avoid extremely long lines. The mouse wheel scrolls up-down fine, left-right is a PITA. You could break that long comment to 2 lines.
Suggested implementation:
#!/bin/bash
# Get number of cores
CORECOUNT=$(grep -c ^processor /proc/cpuinfo)
# Use top, skip the first 7 rows, count the sum of the values
# in column 9 - the CPU column, do some simple rounding at the end
CPUUSAGE=$(top -bn 1 | awk -v n=$CORECOUNT 'NR > 7 { s += $9 } END { print int(s / n + .5); }')
echo $CPUUSAGE
Btw, do you really need $CPUUSAGE
? If not, just omit the variable, change the last line:
top -bn 1 | awk -v n=$CORECOUNT 'NR > 7 { s += $9 } END { print int(s / n + .5); }'
(I used n
as the Awk variable name mainly to make my answer fit on the page without scrolling ;-) Feel free to name it corecount
or as you like.)