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.

2

1 Answer 1

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

.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.