1

Hi I would like to compare 2 float numbers in bash but I haven't find anything that works properly. My actual code is the following:

  if [ $(echo " 0.5 > $X " | bc -l )==1 ]
  echo grande
  fi
  if [ "$(bc <<< "$X - 0.5")" > 0 ] ; then
  echo 'Yeah!'
  fi

What happens is that no matter if the X is bigger or smaller than 0.5, it always echos both sentences and I don't know why. I know the X is bigger or smaller than 0.5 because I also echo it and I can see it.

  • Possible duplicate of http://stackoverflow.com/questions/15224581/floating-point-comparison-with-variable-in-bash – Eric Renouf Apr 30 '15 at 00:04
  • 1
    when compare numeric with `[ ]` you should use `-gt` not `>`. http://www.tldp.org/LDP/abs/html/refcards.html – Dyno Fu Apr 30 '15 at 00:14

1 Answers1

2

In bash, you need to be very careful about spacing. For example:

if [ $(echo " 0.5 > $X " | bc -l )==1 ]; then
  echo grande
fi

Here, there are no spaces around the ==, so it'll be interpreted as:

if [ 0==1 ]; then
fi

Believe it or not, this condition is always true.

Consider:

if [ "$(echo " 0.5 > $X " | bc -l )" == 1 ]; then
  echo grande
fi

.

ctt
  • 1,405
  • 8
  • 18