M BUZZ CRAZE NEWS
// general

Compare a variable that can have numeric or string as value

By Sarah Rodriguez

I have a variable named Seconds_Behind_Master from one of my scripts. The problem is that this variable can either have a numeric value or can also take a string NULL as its value. Now, when I try to execute this script in shell it gets executed but gives a warning like this:

[: Illegal number: NULL

I believe it is due to the fact that in this case the value is NULL but when it compares it with numeral value 60 it gives this warning. How can I rectify it?

2

2 Answers

In this case you should use an arithmetic evaluation - (( expression )):

if (( $Seconds_Behind_Master >= 60 )); then echo "replication delayed > 60."
elif [ "$Seconds_Behind_Master" = "NULL" ]; then echo "Delay is Null."
fi

If you want to respect the standard POSIX, then you can use:

if echo $Seconds_Behind_Master | egrep -q '^[0-9]+$' && [ "$Seconds_Behind_Master" -ge "60" ] ; then echo "replication delayed >= 60."
elif [ "$Seconds_Behind_Master" = "NULL" ]; then echo "Delay is Null."
fi

More about: Shell - Test a numeric variable.

Check if the var is NULL first, then check if it is >= 60. Consider this code:

if [ "$Seconds_Behind_Master" = "NULL" ]; then echo "Delay is Null."
elif [ "$Seconds_Behind_Master" -ge 60 ] 2>/dev/null; then echo "replication delayed >= 60."
else echo "Seconds_Behind_Master is neither NULL or >= 60"
fi

You can also replace the line

elif [ "$Seconds_Behind_Master" -ge 60 ] 2>/dev/null; then

with

elif [[ "$Seconds_Behind_Master" -ge 60 ]]; then

if you prefer that and are using a shell which supports the [[ syntax.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy