我只是不知道如何确保传递给脚本的参数是否为数字。

我只想这样做:

test *isnumber* $1 && VAR=$1 || echo "need a number"

有什么帮助吗?


当前回答

[[ $1 =~ ^-?[0-9]+$ ]] && echo "number"

别忘了——包括负数!

其他回答

没有抨击(即使在System V sh中也有效),

case $string in
    ''|*[!0-9]*) echo bad ;;
    *) echo good ;;
esac

这将拒绝空字符串和包含非数字的字符串,接受其他所有内容。

负数或浮点数需要一些额外的工作。一个想法是排除-/。在第一个“bad”模式中,添加更多包含不正确用法的“bad“模式(?*-*/*.*.*)

[[ $1 =~ ^-?[0-9]+$ ]] && echo "number"

别忘了——包括负数!

只是对“玛丽”的跟进。但因为我没有足够的代表,所以无法将此作为评论发布到该帖子中。无论如何,这是我使用的:

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

公认的答案在这里行不通,我在MacOS上。以下代码有效:

if [ $(echo "$number" | grep -c '^[0-9]\+$') = 0 ]; then 
    echo "it is a number"
else
    echo "not a number"
fi

一种方法是使用正则表达式,如下所示:

re='^[0-9]+$'
if ! [[ $yournumber =~ $re ]] ; then
   echo "error: Not a number" >&2; exit 1
fi

如果值不一定是整数,请考虑适当地修改正则表达式;例如:

^[0-9]+([.][0-9]+)?$

…或,用符号处理数字:

^[+-]?[0-9]+([.][0-9]+)?$