我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
当前回答
以下是我编写的脚本,用于与Nagios的脚本集成,到目前为止运行正常
#!/bin/bash
# Script to test variable is numeric or not
# Shirish Shukla
# Pass arg1 as number
a1=$1
a=$(echo $a1|awk '{if($1 > 0) print $1; else print $1"*-1"}')
b=$(echo "scale=2;$a/$a + 1" | bc -l 2>/dev/null)
if [[ $b > 1 ]]
then
echo "$1 is Numeric"
else
echo "$1 is Non Numeric"
fi
EG:
# sh isnumsks.sh "-22.22"
-22.22 is Numeric
# sh isnumsks.sh "22.22"
22.22 is Numeric
# sh isnumsks.sh "shirish22.22"
shirish22.22 is Non Numeric
其他回答
我在看答案。。。意识到没有人想到浮点数(带点)!
使用grep也很棒。-E表示扩展正则表达式-q表示安静(不回声)-qE是两者的组合。
要直接在命令行中测试,请执行以下操作:
$ echo "32" | grep -E ^\-?[0-9]?\.?[0-9]+$
# answer is: 32
$ echo "3a2" | grep -E ^\-?[0-9]?\.?[0-9]+$
# answer is empty (false)
$ echo ".5" | grep -E ^\-?[0-9]?\.?[0-9]+$
# answer .5
$ echo "3.2" | grep -E ^\-?[0-9]?\.?[0-9]+$
# answer is 3.2
在bash脚本中使用:
check=`echo "$1" | grep -E ^\-?[0-9]*\.?[0-9]+$`
if [ "$check" != '' ]; then
# it IS numeric
echo "Yeap!"
else
# it is NOT numeric.
echo "nooop"
fi
要匹配JUST整数,请使用以下命令:
# change check line to:
check=`echo "$1" | grep -E ^\-?[0-9]+$`
跟进2013年10月David W的回答,如果使用expr,这可能会更好
test_var=`expr $am_i_numeric \* 0` >/dev/null 2>&1
if [ "$test_var" = "" ]
then
......
如果是数字,则乘以1将得到相同的值(包括负数)。否则,您将得到空值,您可以进行测试
公认的答案在这里行不通,我在MacOS上。以下代码有效:
if [ $(echo "$number" | grep -c '^[0-9]\+$') = 0 ]; then
echo "it is a number"
else
echo "not a number"
fi
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_04_03.html
您也可以使用bash的字符类。
if [[ $VAR = *[[:digit:]]* ]]; then
echo "$VAR is numeric"
else
echo "$VAR is not numeric"
fi
数字将包括空格、小数点和“e”或“e”表示浮点。
但是,如果指定C样式十六进制数,即“0xffff”或“0xffff”,则[[:digital:]]返回true。这里有点陷阱,bash允许你做一些类似“0xAZ00”的事情,但仍然将其算作一个数字(这不是GCC编译器的一些奇怪的怪癖,允许你对16以外的基使用0x符号吗??)
如果您的输入完全不可信,除非您想接受十六进制数字,否则您可能需要在测试“0x”或“0x”之前测试它是否为数字。这将通过以下方式实现:
if [[ ${VARIABLE:1:2} = "0x" ]] || [[ ${VARIABLE:1:2} = "0X" ]]; then echo "$VAR is not numeric"; fi
我使用expr。如果尝试将零添加到非数值,则返回非零:
if expr -- "$number" + 0 > /dev/null 2>&1
then
echo "$number is a number"
else
echo "$number isn't a number"
fi
如果需要非整数,可以使用bc,但我不认为bc有完全相同的行为。将零添加到非数字会得到零,它也会返回值零。也许你可以把bc和expr结合起来。使用bc将零添加到$number。如果答案为0,则尝试expr验证$number不为零。