for over a list
for f in *.txt; do
echo "processing $f"
doneThe list is anything: glob results, an explicit list, command substitution, an array.
for over a range
# C-style (bash/zsh)
for ((i=0; i<10; i++)); do echo $i; done
# brace expansion
for i in {1..10}; do echo $i; done
for i in {1..10..2}; do echo $i; done # stepfor over array
files=("a.txt" "b.txt" "c.txt")
for f in "${files[@]}"; do echo "$f"; done"${arr[@]}" expands to one quoted token per element. "${arr[*]}" joins them into one string with IFS — almost always wrong.
while
i=0
while [[ $i -lt 5 ]]; do
echo $i
((i++))
done
# Read a file line by line
while IFS= read -r line; do
echo "> $line"
done < input.txtIFS= read -r is the safe form — preserves leading/trailing whitespace and backslashes. Use it for any line-by-line file read.
until — the inverse of while
until ping -c1 server.local; do
echo 'waiting...'
sleep 5
donebreak and continue
break exits the current loop. break 2 exits two nested levels. continue skips to the next iteration.