1

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
shellter
  • 36,525
  • 7
  • 83
  • 90
charan
  • 21
  • 4
  • what is the output of `uname -srv ; echo $SHELL`? Good luck. – shellter Dec 06 '19 at 15:32
  • I want to use /bin/sh interpreter, Please find the reply of uname -srv Linux 4.15.0-29-generic #31~16.04.1-Ubuntu SMP Wed Jul 18 08:54:04 UTC 2018 /bin/bash – charan Dec 07 '19 at 12:25
  • Do you get valid output from `for (( i=1 ; i<3; i++)) ; do echo i=$i ; done` ? Or an error message, `syntax error: bad for loop variable` ? Good luck. – shellter Dec 07 '19 at 17:38

1 Answers1

0

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 
shellter
  • 36,525
  • 7
  • 83
  • 90
Harish
  • 341
  • 1
  • 13
  • Yes its working for me (I don't want to use sed cmd ) is there any alternative ? – charan Dec 07 '19 at 12:30
  • 1
    you're already using `sed`. Does your version of shell work with `echo ${CPU##* }` ?(this should give you the last word inside of `$CPU`. Good luck. – shellter Dec 07 '19 at 16:16