Monday, September 5, 2011

shell script to get cpu usage

####################################################
#  Author  : Saurabh Gupta                         #
#  Created : 9:30 AM 9/5/2011                      #
#  shell script to calculate the cpu usage         #
#  It will display the idle % of the cpu           #
####################################################

#!/bin/bash

id=0; tot=0; p_id=0; p_tot=0;

for ((i=0; $i < 100; ++i )) ; do

    p_id=$id; p_tot=$tot;
    x=`cat /proc/stat | grep -w cpu`;
    id=`echo $x | cut -d " " -f 5`;
    tot=0;
    for f in `echo $x`; do
        tot=$(($tot + $f));
    done;

    echo "idle cpu usage% = "$((($id - $p_id)*100/($tot - $p_tot)));

    sleep 3;
done

11 comments:

  1. its working. thanks bro. please post some more scripts.

    ReplyDelete
  2. thanks man. great script.

    ReplyDelete
  3. Is not working for me...it is giving error...pls find below...pls give reply asap...

    cpuUsage.sh: 6: Syntax error: Bad for loop variable

    ReplyDelete
  4. Hi,

    I tried with that again. it is working as expected:

    [sgupta@rhel55x86 scripts]$ . ./get-cpu-usage.sh
    idle cpu usage% = 99
    idle cpu usage% = 99
    [sgupta@rhel55x86 scripts]$

    You put your email id to me @ "saurabhgupta0527@gmail.com". I will mail you my working copy.

    --Saurabh Gupta

    ReplyDelete
  5. Thanks for ur reply saurabh,I tried again with that code.It is working now...Thanks a lot once again.

    ReplyDelete
  6. pleasure to hear that ... :)

    post me if you need any script and code for your requirement.

    Thanks,
    Saurabh Gupta

    ReplyDelete
  7. I get following error

    line 25: ( - 0)*100/(0 - 0): division by 0 (error token is ")")

    Can anyone help?

    ReplyDelete
    Replies
    1. Hi,

      This is a common error for windows user. Seems like you have used any windows editor. do a dos to unix for your file. See below,

      dos2unix your-file-name

      run again it will work.

      Delete
  8. Hi,

    We can better take the value from vmstat "id column" right? Any differences between these 2

    # vmstat 1
    procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu-----
    r b swpd free buff cache si so bi bo in cs us sy id wa st
    0 0 9996 60296 13416 267052 0 0 19 81 396 977 11 4 84 1 0
    0 0 9996 59936 13416 267080 0 0 0 0 1054 918 29 2 69 0 0

    ReplyDelete
  9. First reported "idle cpu usage%" is always 88 why so?

    ReplyDelete