Loops
Iterate with for, while, and until, and read files safely.
for loops (words)
for x in a b c; do
echo "$x"
done
for f in src/*.js; do
[[ -e $f ]] || continue # handle no-match when nullglob is off
echo "$f"
done
C-style loop
for (( i = 0; i < 3; i++ )); do
echo "$i"
done
while / until
count=0
while (( count < 3 )); do
echo "$count"; ((count++))
done
until ping -c1 example.com &>/dev/null; do
sleep 1
done
Reading files safely
# Avoid: while read line; do ...; done < file # breaks on spaces/backslashes
# Prefer:
while IFS= read -r line; do
printf '%s\n' "$line"
done < input.txt
IFS= prevents trimming; -r disables backslash escapes.
Loop control
breakto exit the loopcontinueto skip to next iteration
Summary
- Use
forfor words/globs, C-style for counters,while/untilfor conditions - Read files with
IFS= read -rto preserve contents