Comparing float values in bash

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.

Upvotes: 1

Views: 4102

Answers (1)

ctt
ctt

Reputation: 1435

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

.

Upvotes: 2

Related Questions