1

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.

Is there also a way to go by increments of 0.5 in the loop?

Thank you!

3
  • 5
    Not really. bash does not implement floating-point arithmetic. Commented Oct 25, 2013 at 22:38
  • No you cannot increment with decimal. What can you do is multiply by a power of 10 what you need then divide back before you use in the code below. Commented Oct 25, 2013 at 22:41
  • 1
    also asked at askubuntu.com/q/365875/10127 Commented Oct 26, 2013 at 2:59

4 Answers 4

1

If you really want to use floating point in bash then you will find bc useful.

say you want 10 iterations, each of size 0.5

#!/bin/bash

Initial=1
Step=0.5
Count=10

for (( i=0; i < $Count; i++ ))
do
 Value=$(echo "$Initial + ( $Step * $i )" | bc)
 echo $Value
done

Will print:

$ ./t.sh 
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
5.5

Alternatively exit the loop based upon Value thusly:

Initial=1
Step=0.5
Value=$Initial
TermValue=6.1

for (( i=0; $(echo "$Value < $TermValue" | bc); i++ ))
do
 Value=$(echo "$Value + $Step" | bc)
 echo $Value
done
Sign up to request clarification or add additional context in comments.

Comments

0

It's not possible to use floats in bash, but you can

#!/bin/bash

for (( i=5; $i <100; i+=10 )); do
    (( c = $i + 10 ))
    echo "${i: 0:-1}.${i: -1} + ${c: 0:-1}.${c: -1}"
done

i.e. multiply everything by 10 and then print the first n-1 digits, a decimal point and then the last digit. Of course this is very limited in being useful.

Comments

0

The shell itself won't support floats, but you can use bc if it's available, or awk, which is almost always available. Both will support floating point operations (so will perl, python, and some other tools)

AirBoxOmega:~ d$ printf ".%i %i 3.14\n" {1..16}
.1 2 3.14
.3 4 3.14
.5 6 3.14
.7 8 3.14
.9 10 3.14
.11 12 3.14
.13 14 3.14
.15 16 3.14

AirBoxOmega:~ d$ printf ".%i %i 3.14\n" {1..16}|awk '{print $1*$2/$3}'
0.0636943
0.382166
0.955414
1.78344
2.86624
0.420382
0.579618
0.764331

AirBoxOmega:~ d$ printf ".%i * %i /  3.14\n" {1..16}|bc -l
.06369426751592356687
.38216560509554140127
.95541401273885350318
1.78343949044585987261
2.86624203821656050955
.42038216560509554140
.57961783439490445859
.76433121019108280254

Comments

0

You can use seq and bc:

for i in $(seq 0.5 10);   do  
  c=$(echo "$i+1" | bc);   
  echo $i "+" $c; 
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.