Bash脚本:测试浮点数是否在一定范围内,包括负数
我试图测试变量Bash脚本:测试浮点数是否在一定范围内,包括负数,bash,comparison,bc,Bash,Comparison,Bc,我试图测试变量$test是否介于-0.9和0.9之间。以下代码适用于数字,但如果$test是小写字母,则表示它是介于-0.9和0.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"
$test
是否介于-0.9
和0.9
之间。以下代码适用于数字,但如果$test
是小写字母,则表示它是介于-0.9
和0.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
test=a
如果($(echo“$test>=-0.9”| bc-l))&($(echo“$test替换:
if (( $( echo "$test >= -0.9" |bc -l) )) && (( $(echo "$test <= 0.9" |bc -l) )); then
if($(echo“$test>=-0.9”| bc-l))&($(echo“$test-0.9&&&$test-0.9&&&$test重构代码以使用Awk可能更有效,尽管它需要了解shell的一些模糊之处
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
如果awk-v number=“$test””结束{exit!(\
数字!~/[^0-9.]/&&number!~/\..*./&&\
数字>=-0.9&&number
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