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.

AHalbert
  • 316
  • 5
  • 23
  • What exactly do you want to do? If $? is an integer, it is never equal to 4.186 – BeniBela Feb 19 '13 at 00:55
  • please go through the link : http://stackoverflow.com/questions/9939546/comparison-of-integer-and-floating-point-numbers-in-shell-script – user1428716 Feb 19 '13 at 00: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. – AHalbert Feb 19 '13 at 00:56
  • http://www.linuxjournal.com/content/floating-point-math-bash they used bc – zb' Feb 19 '13 at 01:01

1 Answers1

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.

amdn
  • 11,314
  • 33
  • 45
  • 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. – AHalbert Feb 19 '13 at 01:06
  • 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. – AHalbert Feb 19 '13 at 01:16
  • 1
    You are using `$?` which is the return code from a command, see http://stackoverflow.com/questions/6834487/what-is-the-variable-in-shell-scripting 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. – amdn Feb 19 '13 at 01:16
  • Oh alright, that makes sense. I will take that into account. Thank you very much! – AHalbert Feb 19 '13 at 01:16
  • 1
    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. – amdn Feb 19 '13 at 01:19
  • Great! I appreciate your explanations. I will upvote when I am able! – AHalbert Feb 19 '13 at 01:25
  • This works. Full example is here https://github.com/Krishnom/bash-scripts/blob/master/compare_float_int.bash – Krishnom Aug 02 '22 at 06:35