How do I test if a variable is a number in Bash?


I just can't figure out how do I make sure an argument passed to my script is a number or not.

All I want to do is something like this:

test *isnumber* $1 && VAR=$1 || echo "need a number"

Any help?

2/5/2017 5:12:42 PM

Accepted Answer

One approach is to use a regular expression, like so:

if ! [[ $yournumber =~ $re ]] ; then
   echo "error: Not a number" >&2; exit 1

If the value is not necessarily an integer, consider amending the regex appropriately; for instance:


...or, to handle numbers with a sign:

8/26/2018 12:40:36 AM

Without bashisms (works even in the System V sh),

case $string in
    ''|*[!0-9]*) echo bad ;;
    *) echo good ;;

This rejects empty strings and strings containing non-digits, accepting everything else.

Negative or floating-point numbers need some additional work. An idea is to exclude - / . in the first "bad" pattern and add more "bad" patterns containing the inappropriate uses of them (?*-* / *.*.*)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow