Check if variable is a number

if [ "$testnum" -eq "$testnum" 2>/dev/null ]; then echo It is numeric; fi
Using the standard numeric comparison but suppressing the STDERR output acts as the simplest way to check a value is numeric. See sample output for some examples.
Sample Output
$ export testnum=123
$ if [ "$testnum" -eq "$testnum" 2>/dev/null ]; then echo It is numeric; fi
It is numeric
$ [ "$testnum" -eq "$testnum" 2>/dev/null ] && echo It is numeric
It is numeric
$ export testnum=123xxx
$ if [ "$testnum" -eq "$testnum" 2>/dev/null ]; then echo It is numeric; fi
$ [ "$testnum" -eq "$testnum" 2>/dev/null ] && echo It is numeric

By: jgc
2009-10-09 14:57:27

3 Alternatives + Submit Alt

What Others Think

Try this. export testnum=" " # a space This will still echo out It is numeric.
uberwrensch · 658 weeks and 3 days ago
Accepting space is a feature, since the Bash shell usually assumes null values are zero for arithmetic purposes. If that's not your purpose, then yeah this check isn't appropriate.
ashawley · 658 weeks and 3 days ago
if you're talking about bash, and not plain sh: [[ $testnum =~ ^[0-9]+$ ]] && echo is a number yes -- that's a real regex. Dont put slashes around it (took me a while to realise that when I first tried this a few months ago!)
sitaram · 658 weeks and 1 day ago
@sitaram: make that a command and I'll vote for it
ashawley · 657 weeks and 6 days ago
This fails for numbers such as: testnum=345.56 testnum=1e10 testnum=0xff
CJK · 34 weeks and 2 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: