Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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

I tried using the following script:

#!/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 .5.

share|improve this question
2  
Why exactly do you need this? You can't have half an iteration in a for loop so it's a syntax error –  minerz029 Oct 25 '13 at 23:46
    
also asked at stackoverflow.com/q/19600448/7552 –  glenn jackman Oct 26 '13 at 2:59

3 Answers 3

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.

share|improve this answer

Bash itself cannot support floating point numbers, but there is a program called bc that can do decimal arithmetic.

You script should be rewrite to use BC (aka Best Calculator) or another other utility. So, how can you do this? There is no way that you can use for loop since the bash builtin itself doesn't support floating points. Either you use another variable to control inside your loop and use 1 (or 0) as starting point.

share|improve this answer

There is a way to fake fractions, a bit awkward but it is usable in some cases:

#!/bin/bash
{
n=9
echo "$n"

for (( i=5; $i <100; i+=10 ))
do
    let "c=$i+10"
    echo "$(( $i / 10 )).$(( $i % 10 )) + $(( $c / 10 )).$(( $c % 10 ))"
done
}

With div/modulo you can also actually do some nifty (read: awkward) calculations.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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