bash test for number in range (with float numbers)

2019-09-04 07:45发布

问题:

the problem is in this line

elif [  "$(echo $a '>' $v06 | bc -l)"  -eq 1  &&   "$(echo $a '<' $v08 | bc -l)" -eq 1  ];then

How can I test if the number is in range ? I know that there might be other solution for this but I want to solve in this way with bc...

a=0.1
v06=0.6
v08=0.8

if [ "$(echo $a '<' $v06 | bc -l)" -eq 1 ];then
    echo " <0.6"
elif [  "$(echo $a '>' $v06 | bc -l)"  -eq 1  &&   "$(echo $a '<' $v08 | bc -l)" -eq 1  ];then
    echo " <0.6 >0.8"
else
    echo ">1.5"
fi

回答1:

If you really want to use bc:

test1=$(bc -l <<< "${a} < ${v06}")
test2=$(bc -l <<< "${a} > ${v06}")
test3=$(bc -l <<< "${a} < ${v08}")
if [[ ${test1} -eq 1 ]]; then
   blabla
elif [[ ${test1} -eq 1 && ${test2} -eq 1 ]]; then 
   blabla
fi

I recommend to use braces around a variable (so you are sure 06 and 08 won't be append to $v), use double brackets in your tests if you are using operators like &&.



回答2:

Actually the only thing wrong is you're using && inside [ ] which does not work.

Only [[ ]] can contain && for multiple test conditions.

You can put the && outside instead, like this

elif [ "$(echo $a '>' $v06 | bc -l)" -eq 1 ] && [ "$(echo $a '<' $v08 | bc -l)" -eq 1 ]; then 

or even better,

elif [ $(echo "($a > $v06) && ($a < $v08)" | bc -l) -eq 1 ]; then

since bc actually supports the (num1 > num2) && (num1 < num3) notation

p/s: You don't need the quotes around the $( ) since you're only expecting 0 or 1 as return value

p/s2: You can have quotes within $( ) even if it's enclosed in quotes e.g.

"$(echo "1 + 2" | bc -l )" 


回答3:

you can strip the "0." and use the -gt and -lt operators:

v06="$(echo $v06 | sed 's/0.//')"
v08="$(echo $v08 | sed 's/0.//')"




elif [  $a -gt $v06 -a $a -lt $v08 ];then


标签: linux bash shell