Ubuntu – use fractions/decimals in a bash script


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):

echo "$n"
for (( i=.5; $i <10; i++ ));
      let "c=$i+1"
      echo $i "+" $c

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.

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

    That'll echo 0 through 9.5 in 0.5 increments.