我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
当前回答
我喜欢阿尔贝托·扎卡尼的回答。
if [ "$var" -eq "$var" ] 2>/dev/null; then
重要的先决条件:-未生成子壳-未调用RE解析器-大多数shell应用程序不使用实数
但是,如果$var是复杂的(例如,关联数组访问),并且如果数字是非负整数(大多数用例),那么这可能更有效?
if [ "$var" -ge 0 ] 2> /dev/null; then ..
其他回答
以下解决方案也可以用于Bourne等基本shell,而不需要正则表达式。基本上,任何使用非数字的数值求值操作都会导致错误,在shell中,该错误将被隐式视为false:
"$var" -eq "$var"
如:
#!/bin/bash
var=a
if [ -n "$var" ] && [ "$var" -eq "$var" ] 2>/dev/null; then
echo number
else
echo not a number
fi
你也可以测试$?更明确的操作返回代码:
[ -n "$var" ] && [ "$var" -eq "$var" ] 2>/dev/null
if [ $? -ne 0 ]; then
echo $var is not number
fi
标准错误的重定向是为了隐藏bash打印出的“预期整数表达式”消息,以防我们没有数字。
CAVETS(感谢以下评论):
带小数点的数字不被识别为有效的“数字”使用[[]]而不是[]将始终计算为true大多数非Bash shell始终将此表达式求值为trueBash中的行为没有记录,因此可能会在没有警告的情况下发生变化如果值在数字后面包含空格(例如“1 a”),则会产生错误,如bash:[[:1 a:表达式中的语法错误(错误标记为“a”)如果该值与var名称相同(例如i=“i”),则会产生错误,如bash:[[:i:expression递归级别超出(错误标记为“i”
要检查的变量号码=12345或号码=-23234或号码=23.167或号码=-345.234检查数字或非数字echo$number|grep-E'^-?[0-9]*\.?[0-9]*$'>/dev/null根据上述退出状态决定进一步行动如果[$?-eq 0];然后回显“数值”;否则回显“非数字”;传真
这是一个有点粗糙的边缘,但有点新手友好。
if [ $number -ge 0 ]
then
echo "Continue with code block"
else
echo "We matched 0 or $number is not a number"
fi
这将导致一个错误,如果$number不是一个数字,则会打印“非法数字:”,但它不会跳出脚本。奇怪的是,我找不到一个测试选项来测试整数。这里的逻辑将匹配任何大于或等于0的数字。
我使用以下(整数):
## ##### constants
##
## __TRUE - true (0)
## __FALSE - false (1)
##
typeset -r __TRUE=0
typeset -r __FALSE=1
## --------------------------------------
## isNumber
## check if a value is an integer
## usage: isNumber testValue
## returns: ${__TRUE} - testValue is a number else not
##
function isNumber {
typeset TESTVAR="$(echo "$1" | sed 's/[0-9]*//g' )"
[ "${TESTVAR}"x = ""x ] && return ${__TRUE} || return ${__FALSE}
}
isNumber $1
if [ $? -eq ${__TRUE} ] ; then
print "is a number"
fi
只是对“玛丽”的跟进。但因为我没有足够的代表,所以无法将此作为评论发布到该帖子中。无论如何,这是我使用的:
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