Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that a variable is a number in UNIX shell [duplicate]

Tags:

shell

unix

How do I check to see if a variable is a number, or contains a number, in UNIX shell?


2 Answers

if echo $var | egrep -q '^[0-9]+$'; then
    # $var is a number
else
    # $var is not a number
fi
like image 126
Adam Rosenfield Avatar answered Sep 13 '25 05:09

Adam Rosenfield


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)

like image 30
Piotr Lesnicki Avatar answered Sep 13 '25 06:09

Piotr Lesnicki