0
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
PortMan
  • 4,205
  • 9
  • 35
  • 61
  • Bash doesnt support floats in that manner see [here](http://stackoverflow.com/questions/8654051/how-to-compare-two-floating-point-numbers-in-a-bash-script) for a solution. – DrBwts Jul 31 '15 at 19:54
  • The question isn't tagged `bash`, but `bash` shares its lack of floating-point values with POSIX. – chepner Jul 31 '15 at 20:58

1 Answers1

0

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 if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 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
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953