27 June 2006

Bash scripting: checking if a variable is a number

Sometime ago I had a simple problem with bash scripting. I liked to check if a variable is a number or not. First I'd looked up into Advanced Bash Scripting Guide but didn't found anything. So my first approach was:

[ -z "`echo $VARIABLE | tr -d "[:digit:]"`" ]

But I didn't like it because of tr usage. So after some discussion with other people I came to the following solution:

[ $VARIABLE -eq $VARIABLE ]

It works great and could be used in a bash script like this:

if [ $VARIABLE -eq $VARIABLE 2> /dev/null ]; then
echo $VARIABLE is a number
else
echo $VARIABLE isn't a number
fi

7 comments:

Steve said...

Awesome trick - thanks for sharing!

-- Steve

Ben said...

exactly what I needed, thank you.

Ben said...

Very elegant and exactly what I needed, thank you

Eleazar said...

It really work, awesome!!!!! But I couldnt understand how the code works, somebody help me to explain it? Any response would be greatly appreciated. Thanks

****just a newbies in shell scripting.:(

ernetas said...

What's wrong about using tr?

The litle green dwarf(-t) said...

It has been very usefool ... Thank you for this post.

Ed said...

Exactly what I was looking for. Good post