shellprocstat

Capture 4 Element of /proc/stat of CPU line in sh


I am unable to capture CPU[3] to IDLE variable in shell script (/bin/sh)

Code snippet as below:-

while true; do
      CPU=$(sed -n 's/^cpu\s//p' /proc/stat)
      **IDLE=$CPU[3]**                                   # Just the idle CPU time.
      for VALUE in ${CPU} ;
      do
       TOTAL=$((TOTAL+VALUE))
       printf "%s \n\n" $VALUE
       sleep 1
       printf "%s \n" $IDLE
      done
      sleep 0.1
 done

Solution

  • You can try below script for extracting specific string elements from sed command.

    #!/bin/sh
    
    CPU=$(sed -n 's/^cpu\s//p' /proc/stat) 
    IDLE=$((sed -n 's/^cpu\s//p' /proc/stat)| (cut -d' ' -f5))
    printf "IDLE Check %s \n" $IDLE
    printf "CPU: %s \n" $CPU
    

    But I see extracted value is increments by one , I will look into this and update in a while , Good Luck !!!

    I am getting Output as below:

    IDLE Check 286857 /*value is incremented by 2 , i will update in while on this */
    CPU: 32898 
    CPU: 6 
    CPU: 8128 
    CPU: 286855  /* This value is to be extracted as example */
    CPU: 27052 
    CPU: 0 
    CPU: 462 
    CPU: 0 
    CPU: 0 
    CPU: 0