Loop Control
Loop control is essential for managing iteration flow in BASH scripts. The break, continue, and exit commands allow precise control over loop execution, enabling scripts to respond dynamically to conditions. This section explores their usage and best practices.
Break: Exit Loops Prematurely¶
The break command terminates the innermost loop immediately. It is useful for exiting loops when a condition is met, avoiding unnecessary iterations.
Example: A for loop that breaks when a specific item is found.
#!/bin/bash
fruits=("apple" "banana" "cherry" "date")
for fruit in "${fruits[@]}"; do
if [[ "$fruit" == "cherry" ]]; then
echo "Found cherry!"
break
fi
echo "Processing $fruit"
done
Notes:
- break can take an argument (e.g., break 2) to exit a nested loop at a specified level.
- Avoid overusing break in favor of refining loop conditions for clarity.
Continue: Skip Current Iteration¶
The continue command skips the current iteration of a loop and proceeds to the next one. It is ideal for filtering out unwanted entries during iteration.
Example: A while loop that skips even numbers.
#!/bin/bash
count=1
while [[ $count -le 10 ]]; do
if (( count % 2 == 0 )); then
echo "Skipping $count"
continue
fi
echo "Processing $count"
((count++))
done
Notes:
- continue works with for, while, and until loops.
- Use it to refine data processing without terminating the loop.
Exit: Terminate Script Execution¶
The exit command terminates the entire script, not just the loop. It is useful for handling critical errors or signaling script completion.
Example: A loop that exits on a critical error.
#!/bin/bash
for i in {1..5}; do
if [[ $i -eq 3 ]]; then
echo "Critical error at $i!"
exit 1
fi
echo "Step $i completed"
done
Notes:
- exit can take an argument (e.g., exit 0 for success, exit 1 for failure).
- Use exit sparingly in loops to avoid unintended script termination.
Key takeaways¶
- Use
breakto exit loops when a condition is met. - Use
continueto skip specific iterations during processing. - Use
exitto terminate the script, but be cautious of its global effect. - Prioritize clarity by refining loop conditions over frequent use of control commands.
- Understand the difference between loop-specific control and script-level termination.