1

I've written this if, that is obviously not working, and I still can't manage to get over it:

#LASTEFFECTIVEHASH
if (( $(echo "$LASTEFFECTIVEHASHMINVAL < $LASTEFFECTIVEHASH < $LASTEFFECTIVEHASHMAXVAL" | $BC -l) )); then
                echo "$DATESTAMP - LASTEFFECTIVEHASH=$LASTEFFECTIVEHASH is between $LASTEFFECTIVEHASHMINVAL and $LASTEFFECTIVEHASHMAXVAL"|tee -a $LOGFILE
else
                echo "$DATESTAMP - LASTEFFECTIVEHASH=$LASTEFFECTIVEHASH is not between $LASTEFFECTIVEHASHMINVAL and $LASTEFFECTIVEHASHMAXVAL"|tee -a $MSGFILE $LOGFILE
fi

But, when value are out of ranges, it results in this:

20170810003646 - LASTEFFECTIVEHASH=139.2 is between 104.9 and 136.9

I'm following the maths syntax: if x > 104.9 and < 136.9, in maths you write it 104.9 < x < 136.9. But I suspect that bash/bc are behaving differently from my math's teacher.

It would be great if bc won't fail to count up to 137 ;)

2
  • @John1024 Oh, I see, sorry. I got carried away with the title but the question is indeed about a different topic. – Gilles 'SO- stop being evil' Aug 10 '17 at 8:40
  • 1
    @Gilles thank you for reconsidering your decision. I did some research about this kind of issue before writing the post and I didn't find anything compatible to my case. Probably I didn't used right keywords, as I see you completely rewrote the question's title. Thanks a lot for your contribution indeed! – Marco Aug 10 '17 at 10:52
4

Unlike for example python, bc does not support chained comparisons:

a < b < c

To perform both comparisons and require both to be true, use logical-and (requires GNU bc):

(a < b) && (b < c)

For example:

$ a=104.9; b=136; c=136.9; if echo "($a < $b) && ($b < $c)" | bc -l | grep -q 1; then echo True; else echo False; fi
True
$ a=104.9; b=137; c=136.9; if echo "($a < $b) && ($b < $c)" | bc -l | grep -q 1; then echo True; else echo False; fi
False

POSIX bc

If you don't have GNU bc, you can replace logical-and with multiplication:

$ a=104.9; b=136; c=136.9; if echo "($a < $b)*($b < $c)" | bc -l | grep -q 1; then echo True; else echo False; fi
True
$ a=104.9; b=137; c=136.9; if echo "($a < $b)*($b < $c)" | bc -l | grep -q 1; then echo True; else echo False; fi
False
1
  • 1
    thank you very much for your help. It works perfectly for my needs, your oneliner is now part of my script! ;) – Marco Aug 10 '17 at 10:54

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.