2

Just wondering how can I check if a floating point value is within a certain range using "bc" and the conditional statements in bash. Thanks in advance

For example,I want to find out if 17.2 is within the range from 17.5 to 18.2.

Have recently learned that I can use bc to check in a statement like this:

if [ $(bc <<< "$result > 17.5") -eq 1 ]

Have tried to do this if [ $(bc <<< "$result > 17.5") && $(bc <<< "$result <= 18.2") -eq 1 ]

But keep a getting syntax error and also unsure if that's the correct expression or syntax.

4

You can't use && inside single square brackets. You have different options, though:

  1. Use -a inside of [ ... ].

    if [ $(bc <<< "$result > 17.5") -eq 1 -a $(bc <<< "$result <= 18.2") -eq 1 ]
    
  2. Use double square brackets [[ ... ]] that support &&.

    if [[ $(bc <<< "$result > 17.5") == 1 && $(bc <<< "$result <= 18.2") == 1 ]]
    
  3. Use two [ ... ] conditions separated by &&.

    if [ $(bc <<< "$result > 17.5") -eq 1 ] && [ $(bc <<< "$result <= 18.2") -eq 1 ]
    
  4. You can use string compare on the result of the two expressions

    [[ $( bc <<< "$result > 17.5; %result <= 18.2" ) == $'1\n1' ]]
    
  5. bc understands &&, too:

    if [[ $(bc <<< "$result > 17.5 && $result <= 18.2") == 1 ]]
    

I'd prefer 5.

| improve this answer | |
1

Bash can't handle floats.

First we get whether or not they are in the range. If this is true (1) then the number is in the range:

test=$(echo "17.5<$result<18.2" | bc)

Then we check it is true with an if.

if [ $test -eq 1 ]
then
    echo true
else
    echo false
fi
| improve this answer | |
  • Interestingly, 1<1<1 returns 1, as it's interpreted as (1<1)<1, i.e. 0<1. – choroba Jun 11 '15 at 15:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.