Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

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?

like image 438
Flávio Amieiro Avatar asked Apr 30 '09 13:04

Flávio Amieiro


People also ask

How do you check if an input is a number in Linux?

One way is to check whether it contains non-number characters. You replace all digit characters with nothing and check for length -- if there's length there's non-digit characters. If input is 5b for example, it will fail check.

How do I find the value of a variable in bash?

To check if a variable is set in Bash Scripting, use-v var or-z ${var} as an expression with if command. This checking of whether a variable is already set or not, is helpful when you have multiple script files, and the functionality of a script file depends on the variables set in the previously run scripts, etc.


2 Answers

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

re='^[0-9]+$' if ! [[ $yournumber =~ $re ]] ; then    echo "error: Not a number" >&2; exit 1 fi 

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

^[0-9]+([.][0-9]+)?$ 

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

^[+-]?[0-9]+([.][0-9]+)?$ 
like image 104
Charles Duffy Avatar answered Sep 18 '22 23:09

Charles Duffy


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

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

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 (?*-* / *.*.*)

like image 26
jilles Avatar answered Sep 17 '22 23:09

jilles