Testing if a variable is an integer
bash, integer, testing, variables
Solution
As long as you're using bash version >=3 you can use a regular expression:
[[ $a =~ ^-?[0-9]+$ ]] && echo integer
While this bash FAQ mentions inconsistencies in the bash regex implementation in various bash 3.x (should the regex be quoted or not), I think in this case, there are no characters that need quoting in any version, so we are safe. At least it works for me in:
- 3.00.15(1)-release (x86_64-redhat-linux-gnu)
- 3.2.48(1)-release (x86_64-apple-darwin12)
- 4.2.25(1)-release (x86_64-pc-linux-gnu)
$ a=""
$ [[ $a =~ ^-?[0-9]+$ ]] && echo integer
$ a=" "
$ [[ $a =~ ^-?[0-9]+$ ]] && echo integer
$ a="a"
$ [[ $a =~ ^-?[0-9]+$ ]] && echo integer
$ a='hello world!'
$ [[ $a =~ ^-?[0-9]+$ ]] && echo integer
$ a='hello world 42!'
$ [[ $a =~ ^-?[0-9]+$ ]] && echo integer
$ a="42"
$ [[ $a =~ ^-?[0-9]+$ ]] && echo integer
integer
$ a="42.1"
$ [[ $a =~ ^-?[0-9]+$ ]] && echo integer
$ a="-42"
$ [[ $a =~ ^-?[0-9]+$ ]] && echo integer
integer
$ a="two"
$ [[ $a =~ ^-?[0-9]+$ ]] && echo integer
Problem
I would like to test if my variable `$var` is actually an integer or not. How can I please do that?