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:
Awesome trick - thanks for sharing!
-- Steve
exactly what I needed, thank you.
Very elegant and exactly what I needed, thank you
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.:(
What's wrong about using tr?
It has been very usefool ... Thank you for this post.
Exactly what I was looking for. Good post
Post a Comment