且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Bash 中测试变量是否为数字?

更新时间:2023-11-29 15:51:52

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

One approach is to use a regular expression, like so:

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

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

If the value is not necessarily an integer, consider amending the regex appropriately; for instance:

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

...或者,处理带符号的数字:

...or, to handle numbers with a sign:

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