1

Ok, so I've been working around with some results from speedtest-cli and realised that I had some errors due to the fact that bash doesn't seem to correctly handle the change in digits?

Anyways, here is an example ran directly from the terminal :

ubuntu:~$ l1=9.99
ubuntu:~$ l2=10.44
ubuntu:~$ if [[ (($l2 > $l1)) ]]; then echo "Ok"; fi
ubuntu:~$ if [[ (($l2 < $l1)) ]]; then echo "Not ok"; fi
Not ok

Of course, comparing eg. 10.33 and 11.34 would give the right result.

How does this happen and how can I fix it? Is there another way to achieve this comparison?

Thanks

1
  • 3
    bash doesn't support floating point arithmetic, only integer. Commented Feb 21, 2019 at 20:10

1 Answer 1

3

You're using string comparison, not numeric. Inside double square brackets, parentheses are used just for precedence, so your condition is equivalent to

[[ $l2 < $l1 ]]

To use numeric comparison, use double parentheses without the square ones:

(( l2 < l1 ))

Unfortunately, this wouldn't work either, as bash doesn't support floating point arithmetic, only integer.

You need to use an external tool, e.g.

bc <<< "$l1 < $l2"

bc returns 1 for true and 0 for false.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.