Loops
Bash loops are essential for automating repetitive tasks, processing collections of data, and implementing conditional iteration. This section covers for, while, and until loops, along with their use cases for arrays, ranges, and dynamic conditions.
for Loop: Iterating Over Collections¶
The for loop is ideal for iterating over arrays, ranges, or lists of items.
Basic Syntax¶
For example, looping through a list of files:Iterating Over Arrays¶
Ranges with seq or {start..end}¶
Or using seq:Note: The C-style for loop (e.g., for ((i=0; i<5; i++))) is available in Bash 4.0+ but less common for simple iteration.
while Loop: Condition-Based Iteration¶
The while loop executes commands as long as a condition is true.
Basic Syntax¶
Example: Processing input until a sentinel value is found:read -p "Enter a number (0 to exit): " num
while [ "$num" -ne 0 ]; do
echo "You entered: $num"
read -p "Enter a number (0 to exit): " num
done
Reading Lines from a File¶
Caution: Always ensure the condition will eventually become false to avoid infinite loops.
until Loop: Inverse of while¶
The until loop runs commands until a condition is met.
Basic Syntax¶
Example: Waiting for a service to start:until curl -s --head http://localhost:8080 | grep "200 OK" > /dev/null; do
echo "Waiting for service..."
sleep 5
done
This is useful for retry logic or polling scenarios.
Advanced Use Cases¶
- Combining Loops with Arrays/Ranges:
- Looping Over Directory Contents:
Key takeaways¶
- Use
forfor iterating over arrays, ranges, or static lists. - Use
whilefor dynamic conditions that depend on external input or state. - Use
untilfor retry logic or waiting for a specific condition. - Always test loops with
set -xto debug unexpected behavior. - Prefer
foroverwhilefor simple collection iteration unless conditions are required.