2

I'm trying to perform simple math, to check if a variable is greater or equal to "1.5" but I'm getting [: 2.41: integer expression expected

Code:

reSum=$(expr "scale=1;555/230" | bc)

if [ $reSum -ge "1.5" ]; then
...
fi

How can I do floating-point comparisons in shell script?

tripleee
  • 175,061
  • 34
  • 275
  • 318
rabotalius
  • 1,430
  • 5
  • 18
  • 27
  • 2
    From `info expr` `< <= = == != >= >' Compare the arguments and return 1 if the relation is true, 0 otherwise. `==' is a synonym for `='. `expr' first tries to convert both arguments to integers and do a numeric comparison; if either conversion fails, it does a lexicographic comparison using the character collating sequence specified by the `LC_COLLATE' locale. – shellter Jul 30 '13 at 23:21

2 Answers2

9
if echo 555 230 | awk '{exit $1/$2 >= 1.5 ? 0 : 1}'
then
  # ...
fi
Zombo
  • 1
  • 62
  • 391
  • 407
2

Edit:

The shortest solution that works for me:

reSum=$(expr "scale=1;555/230" | bc)

if (( `echo $reSum'>='1.5 | bc` )); then
  # anything
fi

As pointed out by shellter, [ $(expr "$reSum > 1.5" | bc) ] actually does a lexicographic comparison. So, for example, expr "2.4 > 18 | bc" // =>0.

However, (( `echo $reSum'>='1.5 | bc` )) does floating point comparison rather than strings.

lifus
  • 8,074
  • 1
  • 19
  • 24