0

I am trying to compare load average with a threshold value using shell script as i am new to it, i am able to calculate the load but the script is giving me bad number error during the condition and my condition is not working. here is my script

#!/bin/sh

LOGFILE=/root/sy.log
WHOLEFILE=/root/sys.log


while sleep 1;
do
   TOP="$(top -n1)"
   CPU="$(cat /proc/loadavg| awk 'BEGIN{t1=t2=t3=0}{t1+=$1;t2+=$2;t3+=$3;} END {print (t1+t2+t3)/3}')"
   echo $CPU >> $LOGFILE
   CPU=`printf "%d" $CPU`
   Threshold=0.2
   Threshold=`printf "%d" $Threshold`
   if [[ "$CPU" -ge "$Threshold" ]] ;
then
       echo $TOP >> $WHOLEFILE
   fi
done
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Divyansh
  • 1
  • 1
  • 1
  • See also [BashFAQ #22](http://mywiki.wooledge.org/BashFAQ/022). – Charles Duffy Dec 20 '17 at 17:43
  • ...a few nitpicks: Avoid `cat foo | awk ...` in favor of `awk ... foo` or `awk ... – Charles Duffy Dec 20 '17 at 17:45
  • ...nitpicks, continued: Avoid all-caps names for your own variables -- [POSIX specifies all-caps names for use for variables with meaning to the shell or operating system](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html). *Always* quote expansions. Avoid calling `top` when all you need to do is read `/proc/loadavg`. Run your code through http://shellcheck.net/ before asking questions here as a matter of habit. – Charles Duffy Dec 20 '17 at 17:47
  • BTW, logging load average over time is something there are tools to do very efficiently (rolling up high-resolution samples into lower-resolution ones over time to be able to use a guaranteed constant amount of storage). [RRDTool](https://oss.oetiker.ch/rrdtool/) is something of the granddaddy of the genre, but it's inspired a lot of others. – Charles Duffy Dec 20 '17 at 17:50

0 Answers0