我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
当前回答
这将测试数字是否为非负整数。它是独立于外壳的(即没有bashms),只使用外壳内置:
[ ! -z "${num##*[!0-9]*}" ] && echo "is a number" || echo "is not a number";
此答案的先前版本提出:
[ -z "${num##[0-9]*}" ] && echo "is a number" || echo "is not a number";
但这是不正确的,因为它接受任何以数字开头的字符串,正如jilles所建议的那样。
其他回答
没有人建议bash的扩展模式匹配:
[[ $1 == ?(-)+([0-9]) ]] && echo "$1 is an integer"
或使用POSIX字符类:
[[ $1 == ?(-)+([[:digit:]]) ]] && echo "$1 is an integer"
我会这样做:
printf "%g" "$var" &> /dev/null
if [[ $? == 0 ]] ; then
echo "$var is a number."
else
echo "$var is not a number."
fi
注意:这将nan和inf识别为数字。
快速和肮脏:我知道这不是最优雅的方式,但我通常只是在上面加一个零并测试结果。像这样:
function isInteger {
[ $(($1+0)) != 0 ] && echo "$1 is a number" || echo "$1 is not a number"
}
x=1; isInteger $x
x="1"; isInteger $x
x="joe"; isInteger $x
x=0x16 ; isInteger $x
x=-32674; isInteger $x
如果$1不是整数,$(($1+0))将返回0或炸弹。例如:
function zipIt { # quick zip - unless the 1st parameter is a number
ERROR="not a valid number. "
if [ $(($1+0)) != 0 ] ; then # isInteger($1)
echo " backing up files changed in the last $1 days."
OUT="zipIt-$1-day.tgz"
find . -mtime -$1 -type f -print0 | xargs -0 tar cvzf $OUT
return 1
fi
showError $ERROR
}
注意:我想我从来没有想过要检查会使整个脚本爆炸的浮点数或混合类型。。。在我的情况下,我不想再进一步了。我将使用mrucci的解决方案和Duffy的正则表达式-它们似乎是bash框架中最健壮的。。。
你也可以像这样使用“let”:
[ ~]$ var=1
[ ~]$ let $var && echo "It's a number" || echo "It's not a number"
It\'s a number
[ ~]$ var=01
[ ~]$ let $var && echo "It's a number" || echo "It's not a number"
It\'s a number
[ ~]$ var=toto
[ ~]$ let $var && echo "It's a number" || echo "It's not a number"
It\'s not a number
[ ~]$
但我更喜欢使用“=~”Bash 3+运算符,就像这个线程中的一些答案一样。
只是对“玛丽”的跟进。但因为我没有足够的代表,所以无法将此作为评论发布到该帖子中。无论如何,这是我使用的:
isnum() { awk -v a="$1" 'BEGIN {print (a == a + 0)}'; }
如果参数是数字,函数将返回“1”,否则将返回“0”。这对整数和浮点数都有效。用法如下:
n=-2.05e+07
res=`isnum "$n"`
if [ "$res" == "1" ]; then
echo "$n is a number"
else
echo "$n is not a number"
fi