Shell Script by Example: Loops
Iterating through data with this code example covering for loops over lists and C-style numeric ranges, while loops that execute based on conditions, until loops that run until conditions become true, and loop control with break and continue.
Code
#!/bin/bash
# For loop over a list
for color in Red Green Blue; do
echo "Color: $color"
done
# C-style for loop
for ((i=0; i<5; i++)); do
echo "Count: $i"
done
# While loop (runs while condition is true)
count=3
while [ $count -gt 0 ]; do
echo "Countdown: $count"
((count--))
done
# Until loop (runs until condition is true)
n=0
until [ $n -ge 3 ]; do
echo "Until: $n"
((n++))
doneExplanation
The for loop iterates over a list of items, which can be explicit strings, glob patterns matching files (like *.txt), or the output of command substitution. The syntax expands array elements as separate words, preserving spaces within individual elements. Bash also supports C-style for loops with for ((init; condition; update)) syntax, useful for numeric counters and traditional index-based iteration.
The while loop executes its block as long as the control command returns exit status 0 (success). It's commonly used for reading files line-by-line with while read line; do ... done < file, or waiting for conditions to change in monitoring scripts. The until loop is the logical inverse, executing as long as the command returns non-zero (failure), effectively running until the condition becomes true.
Loop control commands break and continue provide fine-grained control over iteration. The break command exits the loop immediately, useful for early termination when a condition is met. The continue command skips the rest of the current iteration and jumps to the next one, helpful for filtering or skipping certain items. Both commands can take an optional numeric argument to break or continue multiple nested loop levels.
Code Breakdown
for color in ... iterates through space-separated items in the list.for ((i=0; i<5; i++)) uses C-style syntax for numeric iteration.while [ $count -gt 0 ] continues while condition returns true (exit 0).until [ $n -ge 3 ] runs until condition becomes true (returns exit 0).
