Loops and Iteration Patterns
Demonstrates for loops, while loops, until loops, and C-style loops with break, continue, and range iteration for various data processing patterns.
Code
#!/usr/bin/env bash
set -euo pipefail
# Iterate over a list
fruits=("apple" "banana" "cherry" "date")
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done
# C-style for loop
for (( i=0; i<5; i++ )); do
echo "Index: $i"
done
# Range iteration
for num in {1..10..2}; do
echo "Odd number: $num"
done
# While loop with counter
count=0
while (( count < 3 )); do
echo "Count: $count"
((count++))
done
# Reading file line by line
while IFS= read -r line; do
[[ "$line" =~ ^# ]] && continue
[[ -z "$line" ]] && continue
echo "Processing: $line"
done < /etc/hosts
# Break and continue
for i in {1..20}; do
(( i % 3 == 0 )) && continue
(( i > 15 )) && break
echo "Value: $i"
doneHow it works
Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.
The core lines of the flow
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
for (( i=0; i<5; i++ )); do
echo "Index: $i"
for num in {1..10..2}; do
echo "Odd number: $num"
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Report a problem with this exampleOpens a pre-filled issue on GitHub.