Thursday, November 04, 2010

Floating calculation in bash (with formatted output)

What I wanted was to get a list of incremental floating numbers, like:
0.0 0.2 0.4 0.6 ... 2.0

It is possible to accomplish this mission in bash, with the help of bc. My own script is listed below:
for i in {0..20..2}
#f=$(printf %3.1f `echo "scale=1; $i/10" | bc`) # old version
printf -v f %3.1f `echo "scale=1; $i/10" | bc` # new version
echo $f

The bc command was used because bash cannot handle floating calculation directly.