1

I have this script:

#!/bin/bash
# rsync using variables

CPU=$(sar 1 5 | grep "Average" | sed 's/^.* //')

if [ $CPU -lt 100 ]
then
   cat mail_content.html | /usr/lib/sendmail -t
else
   echo "Normal"
fi

when I am executing it I am getting the following error message:

./monitor_cpu.sh: line 6: [: 99.25: integer expression expected
Normal

I want it to be able to identify that the number x.x (99.25) will be recognized which is not happening right now.

ErezN
  • 669
  • 2
  • 13
  • 25
  • For portability, you should specify `CPU=$(LANG=C sar 1 5 | grep "Average" | sed 's/^.* //')` – xiawi Jun 29 '17 at 14:40

2 Answers2

1

Alternatively, if CPU is not an integer, you can use bc to compare it.

echo "$CPU < 100" | bc

Then if the result is 1, the value of CPU will be less than 100. So you can do:

[ $(echo "$CPU < 100" | bc) -eq 1 ] && echo yes

Or, you can convert it to integer with printf:

printf '%.0f' "$CPU"
zhenguoli
  • 2,268
  • 1
  • 14
  • 31
0

The problem is that -eq does not compare floats, as explained here. Thus, you need to use bc.

#!/bin/bash
# rsync using variables

CPU=$(LANG=C sar 1 5 | grep "Average" | sed 's/^.* //')

if (( $(echo "$CPU  < 100" |bc -l) ))
then
   cat mail_content.html | /usr/lib/sendmail -t
else
   echo "Normal"
fi
xiawi
  • 1,772
  • 4
  • 19
  • 21