tags:

views:

1762

answers:

4

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
+2  A: 
if echo $var | egrep -q '^[0-9]+$'; then
    # $var is a number
else
    # $var is not a number
fi
Adam Rosenfield
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
A: 

In either ksh93 or bash with the extglob option enabled:

if [[ $var == +([0-9]) ]]; then ...

Darron
+1  A: 

The title doesn't say all. Do you need to check for an integer or for a float as well?