Reputation: 4523
if [ 3 -lt 6 ]; then
echo "It works with ints"
fi
if [ 3.0 -lt 6.0 ]; then
echo "It works with floats"
else
echo "It doesn't work with floats"
fi
Comparing the integers in an "if" works just fine.
But it doesn't work when I do the same thing with floating point numbers, and gives me this output:
+ [ 3.0 -lt 6.0 ]
/tmp/hudson7259224562322746826.sh: 11: [: Illegal number: 3.0
+ echo It doesn't work with floats
It doesn't work with floats
Upvotes: 0
Views: 671
Reputation: 882196
As per the bash
manpage (my emphasis at the end):
arg1 OP arg2
:OP
is one of-eq
,-ne
,-lt
,-le
,-gt
, or-ge
. These arithmetic binary operators return true ifarg1
is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal toarg2
, respectively.Arg1
andarg2
may be positive or negative integers.
In other words, bash
has no native support in comparing floating point values.
If you really want to handle floating point, you're better off choosing a tool that does support it, such as bc
:
n1=3.0 ; n2=6.0
if [[ $(echo "${n1} < ${n2}" | bc) -eq 1 ]] ; then
echo ${n1} is less than ${n2}
fi
Upvotes: 1