Ubuntu – use fractions/decimals in a bash script

bashcalculatorscripts

Is there a certain syntax to use while using fractions or decimals in a bash script?

I tried using the following script (in Ubuntu 12.04):

#!/bin/bash
{
n=9
echo "$n"
for (( i=.5; $i <10; i++ ));
      do
      let "c=$i+1"
      echo $i "+" $c
done
}

This works with i=1, but it generates a syntax error when I put in .5.

Best Answer

Yeah bash only handles integers but you can route around the issue, either by not using bash (Python is very simple to pick up) or by using bc to handle the calculations.

Remember that your condition in your for loop isn't going to work at fractions so you'll need to expand that too.

step="0.5"

for (( i=0; $i<$(bc<<<"10/$step"); i++ )); do
      echo $(bc<<<"$step * $i")
done

That'll echo 0 through 9.5 in 0.5 increments.