The shell can’t do floating point calculations.
If you need to use floating point you either need to use bc - which is a scriptable terminal based calculator.
echo "(1+2)/4" | bc -l
Or using variables:
echo "($a+$b)/$c" | bc -l
Or using variables and storing the result in a variable:
result=$(echo "($a+$b)/$c" | bc -l)
The -l flag causes bc to load a fixed precision library - so it’s not floating point per-se. If you don’t use the -l flag it will only perform integer mathematics.
Also, by default the precision is 20 decimal places. Which is more than enough precision for practical purposes.
But if you need more, or less precision, you can specify the number of decimal places like this:
result=$(echo "scale 2; ($a+$b)/$c" | bc -l)
Above should yield the result to 2 decimal places. Which might be more useful than 20 decimal places.
Alternatively, you could invoke something like the python interpreter to perform the calculation.
It doesn’t have to be python btw. It could be any other scripting language - Perl, ruby, lua etc... whatever “floats” your boat ha ha. I just mentioned python because it’s installed by default on most most, if not all modern distros.
Unfortunately, I don’t have time to put a python example together atm. But in your script, you can run your calculation through python, or some other interpreter.
If I get a chance later I might add a python example!
There are two things wrong there:
1. Expr can only evaluate string or integer expressions.
2. Piping the result from expr to bc is pointless
In what you’ve posted, expr will evaluate the expression and then pass the result to bc. So in that example you’re getting an int result from expr. Piping that to bc is completely redundant, because it just gets passed the integer value from expr.
Ignore expr and just use bc.
The echo command in my bc examples creates an expression which is piped to bc for evaluation. bc evaluates the expression and displays/returns a fixed precision result!