我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
当前回答
我使用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不为零。
其他回答
以下是我编写的脚本,用于与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
跟进2013年10月David W的回答,如果使用expr,这可能会更好
test_var=`expr $am_i_numeric \* 0` >/dev/null 2>&1
if [ "$test_var" = "" ]
then
......
如果是数字,则乘以1将得到相同的值(包括负数)。否则,您将得到空值,您可以进行测试
我喜欢阿尔贝托·扎卡尼的回答。
if [ "$var" -eq "$var" ] 2>/dev/null; then
重要的先决条件:-未生成子壳-未调用RE解析器-大多数shell应用程序不使用实数
但是,如果$var是复杂的(例如,关联数组访问),并且如果数字是非负整数(大多数用例),那么这可能更有效?
if [ "$var" -ge 0 ] 2> /dev/null; then ..
test -z "${i//[0-9]}" && echo digits || echo no no no
${i//[0-9]}将$i值中的任何数字替换为空字符串,请参见man-P“less+/parameter\/”bash-z检查结果字符串的长度是否为零。
如果您还想排除$i为空时的情况,可以使用以下构造之一:
test -n "$i" && test -z "${i//[0-9]}" && echo digits || echo not a number
[[ -n "$i" && -z "${i//[0-9]}" ]] && echo digits || echo not a number
我尝试了超锯片的配方,因为它对我来说似乎是最实用的,但没能奏效。最后,我设计了另一种方法,与其他参数替换方法一样,这次使用正则表达式替换:
[[ "${var//*([[:digit:]])}" ]]; && echo "$var is not numeric" || echo "$var is numeric"
它删除$var中的每一个:digit:class字符,并检查是否剩下一个空字符串,这意味着原始字符串只有数字。
我喜欢这款车的地方是它的占地面积小,灵活性强。在这种形式中,它只适用于非分隔的、以10为基数的整数,当然您可以使用模式匹配来满足其他需要。