BASH脚本:测试是否浮点数在一定范围内,包括负数



我正在尝试测试变量$test是否在-0.90.9之间。以下代码可与数字一起使用,但是如果$test是较低的案例字母,则说它是-0.90.9之间的数字。

是否有更好的方法来执行此操作,因此字母不在该范围内?

test=a
if (( $( echo "$test >= -0.9" |bc -l) )) && (( $(echo "$test <= 0.9" |bc -l) )); then
    echo "${test} is between -0.9 and 0.9"
else
    echo "${test} is NOT between -0.9 and 0.9"
fi

替换:

if (( $( echo "$test >= -0.9" |bc -l) )) && (( $(echo "$test <= 0.9" |bc -l) )); then

(假设GNU或其他增强的BC):

if [[ "$test" =~ ^[[:digit:].e+-]+$ ]] && echo "$test>-0.9 && $test <=0.9" |bc -l | grep -q 1; then

它如何工作

  • [[ "$test" =~ ^[[:digit:].e+-]+$ ]]

    这检查了$test仅包含合法数字字符。

  • &&

    这仅在$test通过数字检查时继续BC测试。

  • echo "$test>-0.9 && $test <=0.9" |bc -l | grep -q 1

    这验证了$test在您想要的范围内。grep -q 1设置用于使用if语句的适当退出代码。

对使用尴尬的代码进行重构可能会更有效,尽管它需要了解有关外壳的一些晦涩的事情。

if awk -v number="$test" 'END { exit !( 
    number !~ /[^0-9.]/ && number !~ /..*./ && 
    number >= -0.9 && number <= 0.9) }' /dev/null
then
    echo "$test is between -0.9 and 0.9"
else
    echo "$test is NOT between -0.9 and 0.9"
fi

如果if检查的退出代码是零,则认为是正确的,这与括号内的真实值相反。因此exit !(...)。Awk的处理模型要求您读取输入文件;我们提供/dev/null,然后将实际逻辑放在END块中,以便即使没有输入也可以执行。

这检查了不超过一个小数点,但是正则是当前不适合指数符号。考虑到John1024的答案中的正则是

,对此增加支持不应该太难了。

最新更新