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

Olivier Samson
  • 609
  • 4
  • 13

1 Answers1

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.

choroba
  • 231,213
  • 25
  • 204
  • 289