Test whether string is a valid integer
[[ $var =~ ^-?[0-9]+$ ]]
- The
^
indicates the beginning of the input pattern - The
-
is a literal "-" - The
?
means "0 or 1 of the preceding (-
)" - The
+
means "1 or more of the preceding ([0-9]
)" - The
$
indicates the end of the input pattern
So the regex matches an optional -
(for the case of negative numbers), followed by one or more decimal digits.
References:
Wow... there are so many good solutions here!! Of all the solutions above, I agree with @nortally that using the -eq
one liner is the coolest.
I am running GNU bash, version 4.1.5
(Debian). I have also checked this on ksh (SunSO 5.10).
Here is my version of checking if $1
is an integer or not:
if [ "$1" -eq "$1" ] 2>/dev/nullthen echo "$1 is an integer !!"else echo "ERROR: first parameter must be an integer." echo $USAGE exit 1fi
This approach also accounts for negative numbers, which some of the other solutions will have a faulty negative result, and it will allow a prefix of "+" (e.g. +30) which obviously is an integer.
Results:
$ int_check.sh 123123 is an integer !!$ int_check.sh 123+ERROR: first parameter must be an integer.$ int_check.sh -123-123 is an integer !!$ int_check.sh +30+30 is an integer !!$ int_check.sh -123cERROR: first parameter must be an integer.$ int_check.sh 123cERROR: first parameter must be an integer.$ int_check.sh c123ERROR: first parameter must be an integer.
The solution provided by Ignacio Vazquez-Abrams was also very neat (if you like regex) after it was explained. However, it does not handle positive numbers with the +
prefix, but it can easily be fixed as below:
[[ $var =~ ^[-+]?[0-9]+$ ]]
Latecomer to the party here. I'm extremely surprised none of the answers mention the simplest, fastest, most portable solution; the case
statement.
case ${variable#[-+]} in *[!0-9]* | '') echo Not a number ;; * ) echo Valid number ;;esac
The trimming of any sign before the comparison feels like a bit of a hack, but that makes the expression for the case statement so much simpler.