for / while
Bash loops: for, while, until, select, infinite loops, and the patterns that read clean.
Linux — Bash loops
EXAMPLE
# ===== for (list) =====
for f in *.txt; do
echo "=== $f ==="
head -3 "$f"
done
# Range:
for i in {1..10}; do echo $i; done
for i in {0..100..5}; do echo $i; done # step of 5
# Brace expansion + variable:
n=10
for i in $(seq 1 $n); do echo $i; done
# ===== for (C-style) =====
for ((i=0; i<10; i++)); do
echo $i
done
# ===== for ... in command output =====
for user in $(cut -d: -f1 /etc/passwd); do
echo "user: $user"
done
# Better: read lines (handles spaces):
while IFS= read -r line; do
echo "got: $line"
done < file.txt
# ===== while =====
i=0
while [ $i -lt 5 ]; do
echo $i
i=$((i + 1))
done
# Read stdin line by line:
while IFS= read -r line; do
echo "got: $line"
done
# ===== until =====
n=5
until [ $n -eq 0 ]; do
echo $n
n=$((n - 1))
done
# ===== select (interactive menu) =====
PS3='Pick an option: '
select opt in start stop quit; do
case "$opt" in
start) echo 'starting'; ;;
stop) echo 'stopping'; ;;
quit) break ;;
esac
done
# ===== break + continue =====
for i in 1 2 3 4 5; do
[ $i -eq 3 ] && continue
[ $i -eq 5 ] && break
echo $i
done
# ===== Infinite loop =====
while true; do
do_thing
sleep 1
done
# ===== Loop over arguments =====
for arg in "$@"; do
echo "$arg"
done
# ===== Common one-liners =====
# Resize many images:
for img in *.png; do convert "$img" -resize 50% "resized-$img"; done
# Run a command N times:
for i in {1..10}; do curl -sf https://example.com > /dev/null; done
# Process files with spaces in names (use find + -print0 + xargs -0):
find . -name '*.log' -print0 | while IFS= read -r -d '' f; do
echo "$f"
done
# ===== Patterns =====
# - Always quote "$var" in loops; never bare
# - while IFS= read -r line for line-by-line reading
# - find -print0 + read -d '' for filenames with spaces
# - Use {n..m} range for fixed sequences
# ===== Pitfalls =====
# - for f in $(ls *.txt) -> breaks on filenames with spaces
# - Unquoted variables -> word splitting
# - Forgetting IFS= -> leading/trailing whitespace stripped
# - 'break N' to exit nested loops; default is 1
Why it matters
Bash loops cover for-list, for-C-style, while, until, select. Quote variables, use IFS= read -r for line iteration, prefer find -print0 for filename safety. Most real-world tasks are a for over files + a one-liner per file.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
for f in *.log; do
gzip "$f"
done
while read line; do
echo "$line"
done < file.txt
Try it Yourself »
Discussion
Loading…