Chapter 2. Looping Lingo
Itâs not just C-style for
loopsâbash includes other syntaxes and styles; some are more familiar to Python programmers, but each has its place. There is a for
loop with no apparent arguments, useful in both scripts and inside functions. Thereâs also an iterator-like for
loop with explicit values and values that can come from other commands.
Looping Constructs
Looping constructs are common in programming languages. Since the invention of the C language, many programming languages have adopted the C-style for
loop. Itâs such a powerful, readable construct because it groups the initialization code, the termination condition, and the iteration code all into one place. For example, in C (or Java, orâ¦):
/* NOT bash */
for
(
i
=
0
;
i
<
10
;
i
++
)
{
printf
(
"%d
\n
"
,
i
);
}
With just a few minor syntax differences, bash follows much the same approach:
for
((
i
=
0
;
i<10
;
i++))
;
do
printf
'%d\n'
"
$i
"
done
Note, especially, the use of double parentheses. Rather than braces, bash uses do
and done
to enclose the statements of the loop. As with C/C++, an idiomatic use of the for
loop is the empty for
loop, giving a deliberate infinite loop (youâll also see while true; do
):
for
((
;;
))
;
do
printf
'forever'
done
But thatâs not the only kind of for
loop in bash. Hereâs a common idiom in shell scripts:
for
value;
do
echo
"
$value
"
# Do more stuff with $value...
done
This looks like something is missing, doesnât it? Where does value
get its values? This wonât do anything ...
Get bash Idioms 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.