Day 3: Conditions and Loops
Goal: Make decisions with
if,[[ ]]andcase, repeat withforandwhile, do arithmetic and read lines safely. At the end,notes-lastgenerates traffic for notes. · Duration: approx. 75 min · Prerequisite: Day 2
Briefing
if command; then …; fichecks the exit code of a command.[[ … ]]is one such command: it compares strings, numbers and files and ends with 0 or 1.casebranches by patterns – more readable than manyelifs.foriterates over a list,whileruns as long as a command reports success,untiluntil it reports success.$(( ))and(( ))do integer arithmetic.- You read lines with
while IFS= read -r zeile– every other form alters them.
notes-last 20 ─► for i in 1..20 ─► case $((i % 10)) ─► GET /notes · POST · 404 …
└─► nginx log grows
Drill 1: if and [[ ]]
source ~/sh-lab/setup/env.sh
mkdir -p ~/sh-lab/tag03 && cd ~/sh-lab/tag03
datei="$NOTES_LOG"
if [[ -f "$datei" ]]; then echo "Log existiert"; fi
if [[ -s "$datei" && -r "$datei" ]]; then echo "nicht leer und lesbar"; fi
name="notes-api"
[[ "$name" == notes-* ]] && echo "Muster passt"
[[ "$name" == "notes-*" ]] || echo "in Anführungszeichen ist * ein Stern"
anzahl=12
if [[ $anzahl -gt 10 ]]; then echo "mehr als zehn"; elif [[ $anzahl -gt 0 ]]; then
echo "ein paar"; else echo "keine"; fi
[[ -z "${leer:-}" ]] && echo "leer ist leer"Expected:
Log existiert
nicht leer und lesbar
Muster passt
in Anführungszeichen ist * ein Stern
mehr als zehn
leer ist leer
| Test | true if | Test | true if |
|---|---|---|---|
-f d |
regular file | -z s |
string empty |
-d d |
directory | -n s |
string not empty |
-s d |
file not empty | a == b |
equal (pattern on the right) |
-x d |
executable | a =~ re |
regular expression matches |
a -eq b |
numbers equal | a -lt b |
number less than |
And a regular expression with captures:
zeile='172.19.0.1 [02/Nov/2026:12:00:01 +0000] "GET /notes HTTP/1.1" 200 69 0.004 curl'
if [[ $zeile =~ \"([A-Z]+)\ ([^ ]+) ]]; then
echo "Methode: ${BASH_REMATCH[1]}, Pfad: ${BASH_REMATCH[2]}"
fiExpected:
Methode: GET, Pfad: /notes
The expression to the right of =~ goes
without quotes; spaces and " are protected
with \. The parentheses fill BASH_REMATCH.
POSIX:
[[ ]],==with patterns and=~exist only in Bash (and zsh, ksh). Insh, it is[ "$a" = "$b" ]– with quotes around every variable.
Save your progress? Sign up for free
Drill 2: case
cat > status <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
for code in "$@"; do
case "$code" in
2??) echo "$code ok" ;;
301|302) echo "$code Umleitung" ;;
4??) echo "$code Fehler beim Client" ;;
5??) echo "$code Fehler beim Server" ;;
*) echo "$code unbekannt" >&2 ;;
esac
done
EOF
bash status 200 302 404 503 abcExpected:
200 ok
302 Umleitung
404 Fehler beim Client
503 Fehler beim Server
abc unbekannt
case compares with the same patterns as file names:
? is one character, * any number,
| separates alternatives. The first matching branch wins,
;; ends it.
Save your progress? Sign up for free
Drill 3: for and arithmetic
for dienst in db notes-api proxy; do echo "Dienst: $dienst"; done
for i in {1..3}; do printf '%s ' "$i"; done; echo
for ((i = 0; i < 10; i += 3)); do printf '%s ' "$i"; done; echo
summe=0
for i in {1..10}; do summe=$((summe + i)); done
echo "Summe 1..10: $summe"
echo "Rest 17 / 5: $((17 % 5)), ganzzahlig: $((17 / 5))"
((summe > 50)) && echo "mehr als 50"Expected:
Dienst: db
Dienst: notes-api
Dienst: proxy
1 2 3
0 3 6 9
Summe 1..10: 55
Rest 17 / 5: 2, ganzzahlig: 3
mehr als 50
Inside $(( )) and (( )), variables don’t
need a $. Bash only does integer arithmetic – decimal
numbers are a job for awk (Day 7).
Warning:
((zaehler++))ends with exit code 1 ifzaehlerwas 0 before – andset -eaborts. Writezaehler=$((zaehler + 1))or((++zaehler)).
Save your progress? Sign up for free
Drill 4: Reading lines
printf '%s\n' " eingerückt" 'mit \ Backslash' "letzte" > zeilen.txt
echo "--- falsch:"
while read zeile; do echo "[$zeile]"; done < zeilen.txt
echo "--- richtig:"
while IFS= read -r zeile; do echo "[$zeile]"; done < zeilen.txt
n=0
while IFS= read -r _; do n=$((n + 1)); done < <(docker ps --format '{{.Names}}')
echo "$n Container laufen"Expected:
--- falsch:
[eingerückt]
[mit Backslash]
[letzte]
--- richtig:
[ eingerückt]
[mit \ Backslash]
[letzte]
3 Container laufen
IFS=preventsreadfrom stripping spaces at the start and end,-rprevents it from interpreting backslashes.< <(command)is process substitution: the loop reads the output ofdocker ps. Withdocker ps | while …, the loop would run in a subshell, andnwould be 0 again afterwards.
Save your progress? Sign up for free
Drill 5: notes-last
For the analyses from Day 6 on, notes needs traffic – with a fixed pattern so that your numbers match those in the book:
cat > ~/sh-lab/werkzeug/bin/notes-last <<'EOF'
#!/usr/bin/env bash
# notes-last – generates traffic for notes: notes-last [count]
set -euo pipefail
url="${NOTES_URL:-http://127.0.0.1:8080}"
anzahl="${1:-50}"
if [[ ! $anzahl =~ ^[0-9]+$ ]]; then
echo "Anzahl muss eine Zahl sein: $anzahl" >&2
exit 2
fi
for ((i = 1; i <= anzahl; i++)); do
case $((i % 10)) in
0) notes-add "Lastnotiz $i" >/dev/null ;;
1 | 2 | 3 | 4) curl -s -o /dev/null -A notes-last "$url/notes" ;;
5 | 6) curl -s -o /dev/null -A notes-last "$url/healthz" ;;
7) curl -s -o /dev/null -A notes-last "$url/version" ;;
8) curl -s -o /dev/null -A notes-last "$url/notes/$i" ;;
9) curl -s -o /dev/null -A notes-last "$url/admin" ;;
esac
done
echo "$anzahl Anfragen an $url"
EOF
chmod +x ~/sh-lab/werkzeug/bin/notes-last
shellcheck ~/sh-lab/werkzeug/bin/notes-last && echo sauber
notes-last 20
notes-last zwanzig; echo "Exit: $?"
tail -3 "$NOTES_LOG"Expected:
sauber
20 Anfragen an http://127.0.0.1:8080
Anzahl muss eine Zahl sein: zwanzig
Exit: 2
172.19.0.1 [02/Nov/2026:12:10:31 +0000] "GET /notes/18 HTTP/1.1" 404 19 0.000 notes-last
172.19.0.1 [02/Nov/2026:12:10:31 +0000] "GET /admin HTTP/1.1" 404 19 0.000 notes-last
172.19.0.1 [02/Nov/2026:12:10:31 +0000] "POST /notes HTTP/1.1" 201 66 0.006 curl/8.18.0
-A notes-lastsets the user agent – that way you can tell in the log who sent the request.notes-adddoesn’t have its own yet (Day 8).- Exit code 2 for incorrect usage is a common convention.
i++is not a problem here: in the header offor ((…)),set -edoesn’t evaluate the expression.
Save your progress? Sign up for free
Checkpoint
grep -c ' notes-last$' "$NOTES_LOG"Expected: 18 requests from notes-last (the two POSTs
went through notes-add).
18
bash ~/sh-lab/tag03/status 418Expected:
418 Fehler beim Client
shellcheck ~/sh-lab/werkzeug/bin/* && echo "alles sauber"Expected:
alles sauber
Challenge
Write notes-wait [seconds]: it waits until
notes-ping reports success, at most as many seconds as
given (default 30), and ends with exit code 1 on timeout.
Note: Bash counts the seconds since the script
started in SECONDS.
Solution
cat > ~/sh-lab/werkzeug/bin/notes-wait <<'EOF'
#!/usr/bin/env bash
# notes-wait – waits until notes responds: notes-wait [seconds]
set -euo pipefail
max="${1:-30}"
until notes-ping >/dev/null 2>&1; do
if ((SECONDS >= max)); then
echo "notes nach ${max}s nicht erreichbar" >&2
exit 1
fi
sleep 1
done
echo "notes bereit nach ${SECONDS}s"
EOF
chmod +x ~/sh-lab/werkzeug/bin/notes-wait
shellcheck ~/sh-lab/werkzeug/bin/notes-wait
notes-wait 5
docker compose -f ~/sh-lab/notes/compose.yaml stop proxy 2>&1 | tail -1
notes-wait 3; echo "Exit: $?"
docker compose -f ~/sh-lab/notes/compose.yaml start proxy 2>&1 | tail -1
notes-waitExpected:
notes bereit nach 0s
Container notes-proxy-1 Stopped
notes nach 3s nicht erreichbar
Exit: 1
Container notes-proxy-1 Started
notes bereit nach 0s
Save your progress? Sign up for free
Enterprise Note
- Wait with a limit: Every loop that waits for something external needs a time limit. Otherwise the deployment hangs, not the service.
- Define exit codes: 0 ok, 1 error, 2 incorrect usage – and document them in the script’s header. Monitoring systems like Nagios use 0–3 with fixed meanings.
- Bash does integer arithmetic with 64 bits. For
percentages, averages and sizes in GiB, use
awkorbc.