Testing if a variable is an integer

Viewed 59015

I would like to test if my variable $var is actually an integer or not. How can I please do that?

7 Answers

You can do this:

shopt -s extglob

if [ -z "${varname##+([0-9])}" ]
then
  echo "${varname} is an integer"
else
  echo "${varname} is not an integer"
fi

The ## greedily removes the regular expression from the value returned by "varname", so if the var is an integer it is true, false if not.

It has the same weakness as the top answer (using "$foo != [!0-9]"), that if $varname is empty it returns true. I don't know if that's valid. If not just change the test to:

if [ -n "$varname" ] && [ -z "${varname##[0-9]}" ]
Related