0

I use bash calculator for floating point calculations and I have to use input redirection and backtick (`) symbol in scripts.

As normal bracket $[math operation] and expr doesn't support float calculation. Is there any other way to do float calculation directly instead of using bc in script. I don't like unnecessary input redirection and backtick (`) symbol for scripts.

#!/bin/bash
x=5
y=6
z=3.3
result=`bc <<end
scale=3
temp_divide=($x / $y)
temp_divide * $z
end`
echo "final result is $result"

1 Answer 1

1

Bash doesn't support floating point arithmetics, so you are stuck with using bc for that. You could use self-written helper functions similar to float_eval, which makes using bc as an inline calculator a little bit easier.

If you don't have to use bash, you could also consider using zsh, which supports floating point operations. Example:

evnu@centraldogma ~ 
% ((val = 1.0))
evnu@centraldogma ~ 
% ((val = 2.2))
evnu@centraldogma ~ 
% echo $val
2.2000000000
evnu@centraldogma ~ 
% ((val += 2.2))
evnu@centraldogma ~ 
% echo $val
4.4000000000

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .