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?
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 negative numbers:
^-?[0-9]+([.][0-9]+)?$
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 ( ?*-* / *.*.* )  
The following solution can also be used in basic shells such as Bourne without the need for regular expressions. Basically any numeric value evaluation operations non-numbers will result in an error which will be implicitly considered as false in shell:
"$var" -eq "$var"
as in:
#!/bin/bash
var=a
if [ "$var" -eq "$var" ] 2>/dev/null; then
  echo number
else
  echo not a number
fi
You can can also test for $? the return code of the operation which is more explicit:
"$var" -eq "$var" 2>/dev/null
if [ $? -ne 0 ]; then
   echo $var is not number
fi
Redirection of standard error is there to hide the "integer expression expected" message that bash prints out in case we do not have a number.
CAVEATS (thanks to the comments below):
[[ ]] instead of [ ] will always evaluate to true  true  bash: [[: 1 a: syntax error in expression (error token is "a")  bash: [[: i: expression recursion level exceeded (error token is "i")  上一篇: .bashrc在ssh登录
下一篇: 如何测试变量是否是Bash中的数字?
