3

What is wrong with the following if-then-else? I never can hit the else.

if [ $result > $value ]; then
   echo HEALTH: OK.  Result is $result  Value is $value
   exit 0
 else
   echo HEALTH: CRITICAL.  Result is $result which is over $value
   exit 2
 fi


# ./check_cw_auto <AWS variables> 5.0
HEALTH: OK. Result is 275593.8 Value is 5.0

# ./check_cw_auto <AWS variables> 10000000.0
HEALTH: OK. Result is 275593.8 Value is 10000000.0

I'm trying to create a nagios bash script. I did try -gt instead of >, but that give an error. Example:

./check_cw_auto <AWS variables> 5.0 
./check_cw_auto: line 30: [: 256497.2: integer expression expected
HEALTH: CRITICAL. Result is 256497.2 which is over 5.0

3 Answers 3

4

In [], two strings are compared lexicographically, not numerically. You want to use -gt or -lt.

Edit: In response to your update, bash does not have floating point logic. You need to use whole numbers.

0
4

As you have a floating point number as part of the comparison you can use bc to do the comparison, bc returns 1 if the comparison is true

if [ $(echo "$result > $value" | bc -q ) -eq 1 ]; then
   echo HEALTH: OK.  Result is $result  Value is $value
   exit 0
 else
   echo HEALTH: CRITICAL.  Result is $result which is over $value
   exit 2
 fi
0

http://mywiki.wooledge.org/BashPitfalls#A.5B.5B_.24foo_.3E_7_.5D.5D

It's being treated as a string comparison.

Use "-gt" instead:

if [ $result -gt $value ]; then

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .