1

I'm trying to compare an integer and a floating point in bash script. I have tried the following:

if [ $? -eq 4.189 ];

which doesn't work because it wants 4.189 to be an integer, and

if [ $? = 4.186 ];

because I thought that that might work. I also tried bc. Any tips on how to do this? Bash newbie here. Thanks so much.

Note: $? is the output from an executable that calculates the volume of a sphere.

4
  • What exactly do you want to do? If $? is an integer, it is never equal to 4.186 Commented Feb 19, 2013 at 0:55
  • please go through the link : stackoverflow.com/questions/9939546/… Commented Feb 19, 2013 at 0:56
  • Oh, you're right. I guess the output is not an integer. -eq expects an integer, I just need a way to compare the output value to 4.189. Sorry, ignorant question. Commented Feb 19, 2013 at 0:56
  • linuxjournal.com/content/floating-point-math-bash they used bc Commented Feb 19, 2013 at 1:01

1 Answer 1

5

This will work

#!/bin/bash
volume=4.189
if [[ $(echo "$volume == 4.189" | bc) -eq "1" ]]; then
    echo Equal
else
    echo Not Equal
fi

or simply put the literal in quotes

#!/bin/bash
volume=4.189
if [[ $volume == "4.189" ]]; then
    echo Equal
else
    echo Not Equal
fi

Notice that of the two ways I showed to compare floating point the preferred is to use bc, it will tell you that 4.1890 is equal to 4.189 whereas the second method is a dumb string compare, they will compare unequal.

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

7 Comments

Ok - so if I use your code, they all come out as correct, and if my code is used, they all come out as incorrect.
the output from the executable, which calculates the volume of a inputted radius. we have to use it because of the sample code that was given to us by the professor.
You are using $? which is the return code from a command, see stackoverflow.com/questions/6834487/… That will always be an integer. The return code is not a good way to do this, first because it is meant to indicate an error condition when not zero and second because you can't pass fractional digits.
Oh alright, that makes sense. I will take that into account. Thank you very much!
You are welcome. Notice that of the two ways I showed to compare floating point the preferred is to use bc, it will tell you that 4.1890 is equal to 4.189 whereas the second method is a dumb string compare, they will compare unequal.
|

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.