Trying to Get Total CPU Usage in Bash

10,686

bash (and expr) can not do floating point arithmetics, you need to take help of bc.

For example :

$ IDLE=$(mpstat | grep "all" | cut -c 92-)

Lets say $IDLE is 77.25.

Now you need bc :

$ IDLE=77.25

$ CPULD="$(bc <<<"100 - $IDLE")"

$ echo "$CPULD"
22.75

bc operates on files, so we can pass the manipulation string via STDIN, although i prefer here strings :

$ echo "100 - 45.34" | bc
54.66

$ bc <<<"100 - 45.34"
54.66

On a different note, to get the IDLE % of CPU, instead of mpstat | grep "all" | cut -c 92- you can do :

mpstat | grep -Po 'all.* \K[^ ]+$'
Share:
10,686

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin about 1 year

    I'm trying to get the CPU's total load with this:

    IDLE=$(mpstat | grep "all" | cut -c 92-)
    
    CPULD=$(expr 100 - $IDLE)
    
    echo $CPULD
    

    but it always returns:

    expr: non-integer argument on the second line. 
    

    I've looked around and everyone says that integers will be automatically recognized in strings, but it doesn't seem to be working.

    EDIT: For those of you who wish to see my full and now-working script, it is here: http://pastebin.com/cFQzz4Up

    • heemayl
      heemayl about 8 years
      Whats the output of mpstat | grep "all" | cut -c 92- ?
    • Pavak Paul
      Pavak Paul about 8 years
      You can use htop $ sudo apt-get install htop && htop
    • Admin
      Admin about 8 years
      Got everything working (sorry that took so long). I tried htop, but I can seem to use grep because it's interactive and refreshes itself. I'm currently using "mpstat 1 1 | grep "Average" | cut -c 92-", but it takes a full second to get an output, and the way I'm using it, it locks up my entire system for the duration of any issued command. As that command takes 1 second to get an output, it freezes for that time. If anyone happens to know a command that can get the usage over the period of maybe 1/10 of a second, or even better instantaneously, I'm open to suggestions.
  • kos
    kos about 8 years
    We posted two almost identical solutions, but indeed you were faster >:), so I'll report here the only difference, i.e. that one may also use mpstat | awk '/all/ {printf "%.2f", $12}' in place of IDLE=$(mpstat | grep "all" | cut -c 92-) (which, FWIW, looks nicer (IMO) and forks 2 processes instead of 3)
  • heemayl
    heemayl about 8 years
    @kos i know nothing about mpstat, that why i asked OP about it first.. :) ..you are right about the concept though in general :)
  • heemayl
    heemayl about 8 years
    @Ben I have not used mpstat but i can confirm you that grep alone can do this by looking at what you are doing..
  • heemayl
    heemayl about 8 years
    @Ben I have installed sysstat, well..you can do mpstat | grep -Po 'all.* \K[^ ]+$'