Bash: comparing a string as an integer

BaSH conditionals are - when it comes to numbers and arithmetic - terribly confusing.

Either of these methods will work:

if [ $((supportLeft)) -lt 1 ] || [ $((yearCompare)) -gt 0 ]

or

if (( supportLeft < 1 || yearCompare > 0 ))

Note both methods treat null values as zero. Depending on your script and environment, this may be advantageous in the sense they won't generate an error message if the value of the variable on either side of the equation is null.


Like this:

[[ $supportLeft -lt 1 || $yearCompare -gt 0 ]]

You can find these and other related operators in man test


This seems to work:

if (( $supportLeft < 1 )) || (( $yearCompare > 0 ))

or

if (( $supportLeft < 1 || $yearCompare > 0 ))

Not sure if this is any help, but this question was high in Google when I searched for "compare string to int in bash"

You can "cast" a string to an int in bash by adding 0

NUM="99"
NUM=$(($NUM+0))

This works great if you have to deal with NULLs as well

NUM=""
NUM=$(($NUM+0))

Make sure there aren't any spaces in the string!

NUM=`echo $NUM | sed -e 's/ //g'`

(Tested on Solaris 10)