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.