Loops
Loops are where scripts save the most time: resize 500 photos, ping 20 servers, process every log file. Bash has three kinds: for, while and until.
for over a list
for fruit in apple banana "dragon fruit"; do
echo "I like $fruit"
doneI like apple I like banana I like dragon fruit
The list can come from anywhere: words, globs, brace expansion or a command's output.
mkdir -p photos && touch photos/{beach,city,forest}.jpg
for f in photos/*.jpg; do
echo "processing $f → ${f%.jpg}.png"
done
for n in {1..5}; do printf "%s " "$n"; done
echo
for user in $(cut -d: -f1 /etc/passwd | head -3); do echo "user: $user"; doneprocessing photos/beach.jpg → photos/beach.png processing photos/city.jpg → photos/city.png processing photos/forest.jpg → photos/forest.png 1 2 3 4 5 user: root user: daemon user: bin
Looping over a glob (photos/*.jpg) is safe even with spaces in file names. Looping over $(command) splits on spaces, so only use it for simple words, never for file names.
C-style for
for (( i = 1; i <= 10; i += 3 )); do
echo "i is $i"
done
for (( i = 3; i > 0; i-- )); do
echo "$i…"
done
echo "liftoff!"i is 1 i is 4 i is 7 i is 10 3… 2… 1… liftoff!
while and until
while repeats as long as its command succeeds; until repeats until it succeeds:
count=1
while (( count <= 3 )); do
echo "attempt $count"
(( count++ ))
done
tries=0
until [[ -f ready.flag ]]; do
(( tries++ ))
echo "waiting for ready.flag (try $tries)"
(( tries == 3 )) && touch ready.flag
done
echo "ready after $tries tries"attempt 1 attempt 2 attempt 3 waiting for ready.flag (try 1) waiting for ready.flag (try 2) waiting for ready.flag (try 3) ready after 3 tries
until is perfect for "wait until the database is up". A real version would sleep between tries.
Reading lines
The most important while loop reads input line by line:
printf "web1 10.0.0.11\nweb2 10.0.0.12\ndb1 10.0.0.20\n" > servers.txt
while read -r host ip; do
echo "$host has address $ip"
done < servers.txt
df -h / | tail -n +2 | while read -r fs size used avail pct mount; do
echo "$mount is $pct full"
doneweb1 has address 10.0.0.11 web2 has address 10.0.0.12 db1 has address 10.0.0.20 / is 7% full
tail -n +2 skips the header line of df.
⚠️ Commands after a
|run in a subshell, so variables set inside… | while readare lost when the loop ends. Usedone < fileordone < <(command)when you need them afterwards.
total=0
printf "3\n4\n5\n" | while read -r n; do (( total += n )); done
echo "with a pipe: $total"
total=0
while read -r n; do (( total += n )); done < <(printf "3\n4\n5\n")
echo "with process substitution: $total"with a pipe: 0 with process substitution: 12
break and continue
breakleaves the loop immediately.continueskips to the next round.
for n in {1..10}; do
(( n % 2 == 0 )) && continue # skip even numbers
(( n > 7 )) && break # stop after 7
echo "odd: $n"
doneodd: 1 odd: 3 odd: 5 odd: 7
Infinite loops
while true runs until something breaks or you press Ctrl + C. It's the shape of every "watch" or "retry" script:
attempt=0
while true; do
(( attempt++ ))
if (( attempt == 3 )); then
echo "connected on attempt $attempt"
break
fi
echo "attempt $attempt failed, retrying…"
sleep 0.1
doneattempt 1 failed, retrying… attempt 2 failed, retrying… connected on attempt 3
Real example: a server health check
#!/usr/bin/env bash
# Check that a few important paths exist and report a summary.
ok=0
failed=0
for path in /etc/hostname /etc/passwd /var/log /opt/app/config.yml; do
if [[ -e $path ]]; then
printf " %-22s ok\n" "$path"
(( ok++ ))
else
printf " %-22s MISSING\n" "$path"
(( failed++ ))
fi
done
echo "$ok ok, $failed missing"
(( failed == 0 )) # the script's exit code: 0 only if nothing is missingbash healthcheck.sh
echo "exit code: $?"/etc/hostname ok /etc/passwd ok /var/log ok /opt/app/config.yml MISSING 3 ok, 1 missing exit code: 1
Ending with a test makes the script's exit code meaningful, so a monitoring tool or CI job knows whether it passed.
Real example: batch rename
mkdir -p shots && cd shots
touch "IMG 001.JPG" "IMG 002.JPG" "IMG 003.JPG"
n=1
for f in *.JPG; do
new=$(printf "holiday-%02d.jpg" "$n")
mv -- "$f" "$new"
(( n++ ))
done
lsholiday-01.jpg holiday-02.jpg holiday-03.jpg
-- tells mv that no more options follow, so a file called -rf.jpg can't be mistaken for an option.
Loops on one line
Handy in the terminal:
for i in 1 2 3; do echo "line $i"; done
for f in /etc/host*; do echo "$f: $(wc -l < "$f") lines"; doneline 1 line 2 line 3 /etc/host.conf: 3 lines /etc/hostname: 1 lines /etc/hosts: 7 lines
Practice
- Print the multiplication table of 7 (
7 x 1 = 7…7 x 10 = 70) with a C-stylefor. - Loop over every
.txtfile in a folder and print its name and line count. - Write a loop that adds up the numbers in a file (one per line) and prints the total.
- Write
wait-for.sh FILEthat checks once a second for up to 10 seconds whetherFILEexists, then reports success or a timeout.
1.What does for f in *.log; do … done loop over?
2.Why is total still 0 after cat nums | while read -r n; do ((total+=n)); done?
3.What does continue do?