Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SH
Bash Scripting
0/12 completed
Beginner
Your first scriptVariables and argumentsQuoting and expansionInput, output and redirection
Intermediate
Conditions and testsLoopsFunctionsArrays and string tricks
Advanced
Text processing: grep, sed and awkError handling and debugging
Pro
Cron and schedulingProduction-ready scripts
Tracks / Bash Scripting / Intermediate

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

bash
for fruit in apple banana "dragon fruit"; do
  echo "I like $fruit"
done
Output
I like apple
I like banana
I like dragon fruit

The list can come from anywhere: words, globs, brace expansion or a command's output.

bash
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"; done
Output
processing 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

bash
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!"
Output
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:

bash
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"
Output
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:

bash
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"
done
Output
web1 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 read are lost when the loop ends. Use done < file or done < <(command) when you need them afterwards.

bash
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"
Output
with a pipe: 0
with process substitution: 12

break and continue

  • break leaves the loop immediately.
  • continue skips to the next round.
bash
for n in {1..10}; do
  (( n % 2 == 0 )) && continue   # skip even numbers
  (( n > 7 )) && break           # stop after 7
  echo "odd: $n"
done
Output
odd: 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:

bash
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
done
Output
attempt 1 failed, retrying…
attempt 2 failed, retrying…
connected on attempt 3

Real example: a server health check

healthcheck.sh
#!/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 missing
bash
bash healthcheck.sh
echo "exit code: $?"
Output
  /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

bash
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
ls
Output
holiday-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:

bash
for i in 1 2 3; do echo "line $i"; done
for f in /etc/host*; do echo "$f: $(wc -l < "$f") lines"; done
Output
line 1
line 2
line 3
/etc/host.conf: 3 lines
/etc/hostname: 1 lines
/etc/hosts: 7 lines

Practice

  1. Print the multiplication table of 7 (7 x 1 = 7 … 7 x 10 = 70) with a C-style for.
  2. Loop over every .txt file in a folder and print its name and line count.
  3. Write a loop that adds up the numbers in a file (one per line) and prints the total.
  4. Write wait-for.sh FILE that checks once a second for up to 10 seconds whether FILE exists, then reports success or a timeout.
✎ Check your understanding

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?

← Conditions and tests