Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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
share|improve this question

3 Answers 3

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.

share|improve this answer
    
That fixed it. Thanks! –  Magd Mar 29 '12 at 20:35

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
share|improve this answer

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.