How to loop through a range of decimal numbers in bash?
Asked Answered
T

3

10

I'd like to generate a sequence of equally spaced decimal numbers.

For example, I want to echo all numbers between 3.0 and 4.5, with step 0.1. I tried $ for i {3.0..4.5..0.1}; do echo $i; done, but this gives an error.

I also tried $ for i in $(seq 3.0 4.5 0.1); do echo $i; done but nothing happens.

Tangram answered 10/6, 2015 at 22:49 Comment(2)
Bash doesn't do floating point numbers. You're best off switching to a different scripting language.Arabic
Is there a command to replace seq that can generate that list so I can use it?Tangram
H
24

I also tried $ for i in $(seq 3.0 4.5 0.1); do echo $i; done but nothing happens.

The order is wrong:

$ for i in $(seq 3.0 0.1 4.5); do echo $i; done
Hyperthyroidism answered 22/6, 2015 at 9:48 Comment(1)
Wow, thanks this works great. Much easier to read than the other methods.Tangram
P
5

If you're looking for a loop from 3.5 to 4.5 in 0.1 steps this would work

for x in {35..45}; do
     y=`bc <<< "scale=1; $x/10"`
     echo $y
done

The same with 0.01 steps

for x in {350..450}; do
         y=`bc <<< "scale=2; $x/100"`
         echo $y
done
Patronizing answered 10/6, 2015 at 23:0 Comment(3)
Thanks, this works. Is bc compulsory for the division?Tangram
Just googled it, now I'm using for x in {30..45}; do y=$(dc <<< "1k $x 10/p"); echo $y; done.Tangram
Yeah, either one works. bash only support integer arithmetic. Therefore, one always needs to use another program...Patronizing
W
-2
 for i in {3.0,4.5,0.1}; do echo $i; done
Went answered 10/6, 2015 at 22:55 Comment(5)
No, that only prints three lines 3.0, 4.5 and 0.1.Tangram
What do you want to print ??Went
A range of decimal numbers, e.g. 3.0 3.1 3.2 3.3 ... 4.5Tangram
@Tangram - The original question was prone to misunderstandings. The syntax shown here is useful for what it was meant to.Demoiselle
What this syntax is "meant to do", however, has no reasonable relationship with "loop[ing] through a range of decimal numbers".Harold

© 2022 - 2024 — McMap. All rights reserved.