๐ Extended Loops and Iteration
Loops enable repetition โ processing files, retrying operations, iterating over data. This section covers all major loop types and their practical applications.
๐งญ For Loop Basics
Iterating Over Items
| for item in apple banana cherry; do
echo "Processing: $item"
done
|
Output:
| Processing: apple
Processing: banana
Processing: cherry
|
Iterating Over Files
| for file in *.txt; do
[ -e "$file" ] || continue # Skip if no matches
echo "Found: $file"
done
|
โ ๏ธ Without [ -e "$file" ], if no .txt files exist, the loop runs once with literal *.txt.
๐งช Numeric Ranges
Bash/Zsh C-Style Loop
| for ((i=1; i<=5; i++)); do
echo "Number: $i"
done
|
Output: 1, 2, 3, 4, 5
POSIX-Compatible Range
| i=1
while [ $i -le 5 ]; do
echo "Number: $i"
i=$((i + 1))
done
|
Using seq (Portable)
| for i in $(seq 1 5); do
echo "Number: $i"
done
|
Or with brace expansion (Bash/Zsh):
| for i in {1..5}; do
echo "Number: $i"
done
|
๐ง While Loop
Repeat while condition is true:
| counter=0
while [ $counter -lt 5 ]; do
echo "Count: $counter"
counter=$((counter + 1))
done
|
This is one of the most common patterns:
| while IFS= read -r line; do
echo "Line: $line"
done < input.txt
|
Explanation:
- IFS= prevents trimming whitespace
- -r prevents backslash interpretation
- < input.txt redirects file into loop
Process multiple files:
| for file in "$@"; do
while IFS= read -r line; do
echo "$file: $line"
done < "$file"
done
|
๐งช Until Loop
Repeat until condition becomes true:
| retries=0
until [ $retries -ge 3 ]; do
echo "Attempt $((retries + 1))"
if curl -s https://api.example.com/health > /dev/null; then
echo "Service is up!"
break
fi
retries=$((retries + 1))
sleep 2
done
|
Useful for retry logic with timeout.
๐ง Loop Control Statements
Break โ Exit Loop Early
| for i in {1..100}; do
if [ $i -eq 42 ]; then
echo "Found the answer!"
break
fi
done
|
Continue โ Skip Current Iteration
| for file in *.log; do
[ -s "$file" ] || continue # Skip empty files
grep ERROR "$file"
done
|
Nested Loop Control
Control outer loop from inner:
| for dir in */; do
for file in "$dir"*; do
if [ "$file" = "STOP" ]; then
break 2 # Exit both loops
fi
echo "Processing: $file"
done
done
|
๐งช Processing Command Output
Iterate Over Command Results
| for pid in $(pgrep nginx); do
echo "Nginx process: $pid"
done
|
โ ๏ธ Be careful with spaces in filenames โ use while read instead:
| pgrep nginx | while IFS= read -r pid; do
echo "Nginx process: $pid"
done
|
Process Array Elements (Bash)
| servers=("web1" "web2" "db1")
for server in "${servers[@]}"; do
ssh "$server" "uptime"
done
|
๐ง Practical Patterns
Batch Processing
Process files in batches of 10:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | count=0
batch=()
for file in *.dat; do
batch+=("$file")
count=$((count + 1))
if [ $count -eq 10 ]; then
process_batch "${batch[@]}"
batch=()
count=0
fi
done
# Process remaining
[ ${#batch[@]} -gt 0 ] && process_batch "${batch[@]}"
|
Parallel Processing with Background Jobs
| for file in *.log; do
analyze_log "$file" &
jobs=$((jobs + 1))
if [ $jobs -ge 4 ]; then
wait # Wait for all background jobs
jobs=0
fi
done
wait # Final wait for remaining jobs
|
Bash/Zsh select creates interactive menus:
| options=("Start" "Stop" "Restart" "Quit")
select opt in "${options[@]}"; do
case $opt in
Start) echo "Starting..."; break ;;
Stop) echo "Stopping..."; break ;;
Restart) echo "Restarting..."; break ;;
Quit) echo "Goodbye"; exit 0 ;;
*) echo "Invalid option" ;;
esac
done
|
| Pattern |
Performance |
Notes |
for i in $(seq) |
โ ๏ธ Slow |
Spawns subshell |
for ((i=0; i<N; i++)) |
โ
Fast |
Built-in arithmetic |
while read |
โ
Fast |
No subshell for input |
for file in * |
โ ๏ธ Medium |
Glob expansion can be slow |
find ... -print0 \| xargs |
โ
Fast |
Handles many files efficiently |
๐งพ Summary
- Use
for for known sets, while for unknown durations.
- Always quote variables in loops:
"$item" not $item.
- Use
break and continue for fine control.
- Prefer
while IFS= read -r for line-by-line processing.
- Batch and parallelize for performance with many items.
๐ Continue to: Functions and Libraries