预期Bash整数表达式

时间:2015-01-06 14:09:27

标签: bash variables conditional-statements

为了满足功能要求,我必须检索一个占空比参数(0-100%,0.01%)。

为了测试,我写了一些简单的东西:

#!/bin/bash
#

if [ "$1" -lt 0 ] || [ "$1" -gt 100 ]
then
    echo "bad param"
else
    echo "ok"
fi  

我获得:

root@:~# ./test.sh 11
ok
root@:~# ./test.sh 11,01
./test.sh: line 4: [: 11,01: integer expression expected
./test.sh: line 4: [: 11,01: integer expression expected
bad param

如何实现这种测试?

1 个答案:

答案 0 :(得分:2)

bash只能在整数算术中运行。如果您需要浮点数,请使用bc之类的外部工具:

if (( $( bc <<< "($1 < 0) || ($1 > 100) " ) )) ; then
    ...
fi

我宁愿切换到整个脚本的更强大的语言(如Perl)/