我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
当前回答
这可以通过使用grep查看所讨论的变量是否与扩展正则表达式匹配来实现。
测试整数1120:
yournumber=1120
if echo "$yournumber" | grep -qE '^[0-9]+$'; then
echo "Valid number."
else
echo "Error: not a number."
fi
输出:有效数字。
测试非整数1120a:
yournumber=1120a
if echo "$yournumber" | grep -qE '^[0-9]+$'; then
echo "Valid number."
else
echo "Error: not a number."
fi
输出:错误:不是数字。
解释
grep和-E开关允许我们使用扩展正则表达式“^[0-9]+$”。此正则表达式表示变量从^开始到$结束只应[]包含0-9 0到9的数字,并且至少应有+1个字符。grep,-q quiet开关关闭任何输出,无论它是否找到任何内容。if检查grep的退出状态。退出状态0表示成功,大于0表示错误。如果grep命令找到匹配项,则其退出状态为0,如果没有找到,则为1;
因此,在if测试中,我们将所有这些放在一起,返回变量$yournumber并|将其通过管道传递给grep,grep使用-q开关与-E扩展正则表达式“^[0-9]+$”表达式匹配。如果grep成功找到匹配项,则grep的退出状态为0,如果没有找到匹配项则为1。如果匹配成功,我们将返回“有效数字”。如果匹配失败,我们将回显“错误:不是数字”。
对于浮球或双打
我们可以将正则表达式从“^[0-9]+$”更改为“^[0-10]*\”。?[0-9]+$'表示浮点或双精度。
测试浮子1120.01:
yournumber=1120.01
if echo "$yournumber" | grep -qE '^[0-9]*\.?[0-9]+$'; then
echo "Valid number."
else
echo "Error: not a number."
fi
输出:有效数字。
测试浮子11.20.01:
yournumber=11.20.01
if echo "$yournumber" | grep -qE '^[0-9]*\.?[0-9]+$'; then
echo "Valid number."
else
echo "Error: not a number."
fi
输出:错误:不是数字。
对于否定词
要允许负整数,只需将正则表达式从“^[0-9]+$”更改为“^\-?[0-9]+$'.
要允许负浮点数或双精度,只需将正则表达式从“^[0-9]*\”更改。?[0-9]+$'到'^\-?[0-9]*\.?[0-9]+$'.
其他回答
一种方法是使用正则表达式,如下所示:
re='^[0-9]+$'
if ! [[ $yournumber =~ $re ]] ; then
echo "error: Not a number" >&2; exit 1
fi
如果值不一定是整数,请考虑适当地修改正则表达式;例如:
^[0-9]+([.][0-9]+)?$
…或,用符号处理数字:
^[+-]?[0-9]+([.][0-9]+)?$
printf '%b' "-123\nABC" | tr '[:space:]' '_' | grep -q '^-\?[[:digit:]]\+$' && echo "Integer." || echo "NOT integer."
删除-\?在grep匹配模式中,如果不接受负整数。
这是一个有点粗糙的边缘,但有点新手友好。
if [ $number -ge 0 ]
then
echo "Continue with code block"
else
echo "We matched 0 or $number is not a number"
fi
这将导致一个错误,如果$number不是一个数字,则会打印“非法数字:”,但它不会跳出脚本。奇怪的是,我找不到一个测试选项来测试整数。这里的逻辑将匹配任何大于或等于0的数字。
易于理解和兼容的解决方案,带有测试命令:
test $myVariable -eq 0 2>/dev/null
if [ $? -le 1 ]; then echo 'ok'; else echo 'KO'; fi
如果myVariable=0,则返回代码为0如果myVariable>0,则返回代码为1如果myVariable不是整数,则返回代码为2
只是对“玛丽”的跟进。但因为我没有足够的代表,所以无法将此作为评论发布到该帖子中。无论如何,这是我使用的:
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