1

I am trying to achieve this in Linux sell

set a=1.2345
set b=2.34

if (abs(a-b)>1.2) then
...
endif

There are several issues that I am facing:

  • dealing with floating point
  • comparison ( using $ vs not using it)
  • calculating the absolute value

I am not able to resolve my issue and handle all of them at once. I have searched many many pages and some solutions don't work for my me. For example I don't seem to have the abs function.

Any help would be greatly appreciated.

  • 1
    Why do you think you should have an `abs` function? Why do you think `abs(a-b)` would call it with that argument? Why do you think `set a=1.2345` sets the bash variable `$a`? Why do you think `endif` ends an `if` statement? Why do you think bash supports floating point numbers? Are you perhaps trying to write `(t)csh` code? – Etan Reisner Jan 21 '15 at 02:47

1 Answers1

3

bash does not do floating point. The standard utility bc does. This uses bc to perform the test that you ask:

a=1.2345
b=2.34

r=$(echo "($a - $b)^2 > 1.2^2" | bc)
if [ "$r" -eq 1 ]
then
        echo True
else
        echo False
fi

Since bc does not have an abs function, the code above uses the simple work-around of squaring each side of the inequality. bc returns 1 if the test is true or 0 if it is false. This output is saved in the variable r. The value of r is tested for equality to 1 with [ "$r" -eq 1 ]. The if statement responds accordingly.

John1024
  • 109,961
  • 14
  • 137
  • 171