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?

1
  • 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. Commented Jul 30, 2013 at 23:21

2 Answers 2

9
if echo 555 230 | awk '{exit $1/$2 >= 1.5 ? 0 : 1}'
then
  # ...
fi
Sign up to request clarification or add additional context in comments.

1 Comment

no external packages needed with this!
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.

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.