Compare a variable that can have numeric or string as value
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: NULLI 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 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."
fiIf 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."
fiMore 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"
fiYou can also replace the line
elif [ "$Seconds_Behind_Master" -ge 60 ] 2>/dev/null; thenwith
elif [[ "$Seconds_Behind_Master" -ge 60 ]]; thenif you prefer that and are using a shell which supports the [[ syntax.
More in general
"Zoraya ter Beek, age 29, just died by assisted suicide in the Netherlands. She was physically healthy, but psychologically depressed. It's an abomination that an entire society would actively facilitate, even encourage, someone ending their own life because they had no hope. Th…"