Repeat work in Bash: for loops over lists and files, while and until loops, C-style counting loops, and controlling them with break and continue.
Why: a for loop runs its body once per item in a list. The list can be literal words, a brace range like {1..5}, or the elements of an array. Note: always quote "$item" so values with spaces stay whole.
#!/usr/bin/env bash
for env in dev staging prod; do
echo "deploying to $env"
done
for i in {1..3}; do
echo "attempt $i"
doneWhy: a glob like *.txt expands to the matching filenames, and the loop visits each one. Quoting "$file" keeps names with spaces intact. Note: if no file matches, the glob stays literal — guard with a [[ -e ]] check when that matters.
#!/usr/bin/env bash
for file in ./logs/*.log; do
[[ -e "$file" ]] || continue # skip if nothing matched
echo "rotating $file"
mv "$file" "$file.old"
doneWhy: a while loop repeats as long as its test stays true — use it to wait for something or to count. The classic file-reading pattern is `while read -r line` fed by an input redirection.
#!/usr/bin/env bash
# Read a file line by line
while read -r line; do
echo "line: $line"
done < input.txt
# Count down
n=3
while [[ "$n" -gt 0 ]]; do
echo "$n"
(( n-- ))
doneWhy: until is while's mirror — it loops UNTIL the condition becomes true (good for "wait for ready"). The C-style for (( ; ; )) form is the most explicit counting loop.
#!/usr/bin/env bash
# Wait until a file appears
until [[ -f /tmp/ready ]]; do
echo "waiting..."
sleep 1
done
# C-style counting loop
for (( i = 0; i < 5; i++ )); do
echo "i = $i"
doneWhy: break leaves the loop entirely; continue skips to the next iteration. Use them to stop early on success or to skip items that do not apply.
#!/usr/bin/env bash
for n in 1 2 3 4 5 6; do
(( n % 2 == 0 )) && continue # skip even numbers
[[ "$n" -gt 4 ]] && break # stop once past 4
echo "odd: $n" # prints 1, 3
done