How to get overall CPU utilization from the bash command line (Linux)

27 Nov 2015

For a little project I worked on I needed to get the CPU utilization as a percentage.
I Google’d the issue and searched for “cpu utilization bash“.

To my surprise there were no elegant solutions. Most just failed to work (on my machine anyway) while others were very inaccurate. For example, some would show the same number over and over again. Some would change the numbers but were not related to CPU utilization at all. Others would sample the CPU utilization over 1 second which is a good idea but wouldn’t work well in my script in my particular case (as my script needed an instant result).

So I came up with the following instant and accurate solution:

This outputs a floating point number between 0.0 and 100.0.
Essentially, we look at the current output of the top using  top -n 1  and then tally up all the numbers for all processes in the CPU usage column. Then we simply divide this number by nproc  (number of processor units available) to get the overall CPU utilization. In this case python handled the floating point division for us (as bash cannot do floating point arithmetic).

Pro tip

You can use the  stress  command ( to stress test your system in order to check the above solution. You should notice that the script will output a number close to 100 if you stress all processor cores.

1 Comment

Posted in Linux


Leave a Reply


  1. nock

    June 6, 2021 at 2:33 AM

    output error : read() in flex scanner failed