我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
当前回答
公认的答案在这里行不通,我在MacOS上。以下代码有效:
if [ $(echo "$number" | grep -c '^[0-9]\+$') = 0 ]; then
echo "it is a number"
else
echo "not a number"
fi
其他回答
我对在shell中直接解析数字格式的解决方案感到惊讶。shell不太适合这一点,因为它是用于控制文件和进程的DSL。下面有很多解析器,例如:
isdecimal() {
# filter octal/hex/ord()
num=$(printf '%s' "$1" | sed "s/^0*\([1-9]\)/\1/; s/'/^/")
test "$num" && printf '%f' "$num" >/dev/null 2>&1
}
将“%f”更改为所需的任何特定格式。
以下是我编写的脚本,用于与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
我使用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不为零。
跟进2013年10月David W的回答,如果使用expr,这可能会更好
test_var=`expr $am_i_numeric \* 0` >/dev/null 2>&1
if [ "$test_var" = "" ]
then
......
如果是数字,则乘以1将得到相同的值(包括负数)。否则,您将得到空值,您可以进行测试
没有人建议bash的扩展模式匹配:
[[ $1 == ?(-)+([0-9]) ]] && echo "$1 is an integer"
或使用POSIX字符类:
[[ $1 == ?(-)+([[:digit:]]) ]] && echo "$1 is an integer"