Loops
There are two kinds of loops in the Bourne shell; for
loops and while
loops. The for
loop is much more common; it is actually a "foreach" loop. Here's an example:
#!/bin/sh for str in one two three four; do echo $str done
Here, for, in, do,
and done
are all shell keywords. The shell executes the code as follows:
The shell sets the variable
str
to the first of the four space-delimited values following the in keyword (one
).The shell runs the
echo
command between thedo
anddone
.The shell goes back to the
for
line, settingstr
to the next value (two
), runs the commands betweendo
anddone
, and repeats the process until it is through with the values following thein
keyword.
Therefore, the output of this script looks like this:
one two three four ...
Get How Linux Works 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.