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.

Please give some alternative.

#!/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"
link|improve this question

feedback

1 Answer

up vote 1 down vote accepted

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
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.