The title says it all - How to check if a variable contains a number in UNIX shell?
+2
A:
Shell variables have no type, so the simplest way is to use the return type test
command:
if [ $var -eq $var 2> /dev/null ]; then ...
(Or else parse it with a regexp)
Piotr Lesnicki
2008-11-21 18:57:34
+2
A:
if echo $var | egrep -q '^[0-9]+$'; then
# $var is a number
else
# $var is not a number
fi
Adam Rosenfield
2008-11-21 19:01:51
I don't know that this is correct, this checks that it is an integer (not a number). I would change the regexp to '[0-9]' to satisfy the problem if the question is in the description ("contains"), and change it to handle non-integer numbers if it is the question in the title ("is").
gpojd
2008-11-21 19:33:37
A:
In either ksh93 or bash with the extglob option enabled:
if [[ $var == +([0-9]) ]]; then ...
Darron
2008-11-21 19:07:04