Looping with Floating-Point Values
Problem
The for
loop with arithmetic
expressions only does integer arithmetic. What do I do for
floating-point values?
Solution
Use the seq command to generate your floating-point values, if your system provides it:
for fp in $(seq 1.0 .01 1.1) do echo $fp; other stuff too done
or:
seq 1.0 .01 1.1 | \ while read fp do echo $fp; other stuff too done
Discussion
The seq command will generate a sequence of
floating-point numbers, one per line. The arguments to
seq are the starting value, the increment, and the
ending value. This is not the intuitive order if
you are used to the C language for
loop, or if you learned your looping from BASIC (e.g., FOR I=4 TO 10 STEP 2
). With
seq the increment is the
middle argument.
In the first example, the $() runs the command in a subshell and
returns the result with the newlines replaced by just whitespace, so
each value is a string value for the for
loop.
In the second example, seq is run as a
command with its output piped into a while
loop that reads each line and does
something with it. This would be the preferred approach for a really
long sequence, as it can run the seq command in
parallel with the while
. The for
loop version has to run
seq to completion and put all of its output on the
command line for the for
statement.
For very large sequences, this could be time- and
memory-consuming.
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.