Exercises — Module 3: Bash Scripting
Rules for every script you write here: starts with
#!/bin/bash+set -euo pipefail; all variables quoted; passesshellcheckwith zero warnings. Treat ShellCheck as your reviewer — install it now (sudo apt install shellcheck).
Part A — Warm-Up Drills (15–20 min each)
Drill 1 — Variables & quoting. Write hello.sh that takes a name as $1, defaults to "world" if missing (${1:-world}), and prints a greeting with the current date via command substitution. Now create a file named two words.txt and extend the script to touch a file named after the argument — prove your quoting handles ./hello.sh "two words" correctly.
✓ ls shows ONE file called two words, not two files.
Drill 2 — Exit codes. Run ls /nonexistent; echo $? then ls /; echo $?. Write a one-liner using && and || that prints "up" if curl -fsS localhost:80 succeeds and "down" otherwise. Then show why set -e changes everything: put a failing command mid-script with and without it.
✓ You can predict the exit-code behavior before running.
Drill 3 — Condition reps. Write checks.sh that, for a path in $1, reports: exists? file or dir? empty? readable/writable/executable? — one [[ ]] test per property. Test it against: a normal file, an empty file, a dir, /etc/shadow (as non-root), a missing path.
✓ All five inputs produce correct, non-crashing output.
Drill 4 — Loop reps. (a) Print server-01 through server-10 zero-padded (printf "server-%02d\n"). (b) Loop over all .log files in a dir printing name + line count. (c) Sum the numbers 1..100 in a while loop. (d) Read /etc/passwd line by line and print only usernames with UID ≥ 1000 (IFS=: trick).
✓ (d) matches the output of the equivalent awk one-liner.
Drill 5 — Arrays & maps. Build an indexed array of 4 fake hostnames; print count, first, last, and iterate. Build an associative array service→port for web/api/db; loop printing name:port sorted by name.
✓ No unquoted ${arr[@]} anywhere (ShellCheck will catch you).
Part B — Guided Labs
Lab 1 — sysinfo.sh (45 min)
Build incrementally, committing to Git after each step (Modules combine!):
log()function with timestamps; print hostname, uptime, kernel.- Add disk usage of
/as a bare percent number (pipedfthroughawk/tr). - Add memory available (
free -hparsing) and top 3 CPU processes (ps aux --sort=-%cpu | head). - Add a
--jsonflag (hand-build the JSON with printf — good quoting practice). - ShellCheck clean; run it on your Module-2 VM via
ssh lab ./sysinfo.sh. ✓ Same script, correct output, on two different machines.
Lab 2 — cleanup.sh — a destructive script done safely (60 min)
Requirements: cleanup.sh <dir> <days> deletes files older than N days.
- Argument validation: exactly 2 args, dir exists, days is a positive integer (regex
[[ $2 =~ ^[0-9]+$ ]]) — clear usage message to stderr and exit 1 otherwise. - Safety rails: refuse
/, refuse paths outside/tmpor/var/tmpunless--forcegiven;${VAR:?}guards. - Dry-run by default: print what WOULD be deleted; require
--applyto actually delete. - Count and report deletions via
find ... -print | wc -lthenfind ... -delete. - Test matrix: dir with old files, dir with none, missing dir, days="abc", the root refusal. ✓ All five tests behave correctly; a colleague could run this without reading the source. That's the bar.
Lab 3 — healthwait.sh — retry logic (30 min)
- Poll
$1(URL) withcurl -fsS, up to${2:-10}attempts, sleeping${3:-3}s between. - Log each attempt
(n/max); exit 0 on success, 1 on exhaustion. - Test against: a running
python3 -m http.server, then against it before starting it (start the server mid-polling from another terminal and watch it succeed). - Add exponential backoff as an option. ✓ This exact script drops into your Module 6 pipeline later — keep it.
Lab 4 — Mini deploy with rollback (90 min) — the module's boss fight
Recreate the section-8 deploy script against a dummy app:
- Dummy app: a dir with
v1/andv2/each containingindex.htmland a fakestart.sh(python http.server on 8080 serving that dir). - Script deploys a version by switching a
currentsymlink and restarting the server; then health-checkscurl localhost:8080for the expected version string. - Make v2's content fail the health check (wrong string) → watch your rollback path fire and restore v1.
- Add: keep only last 3 "releases";
trapcleanup of temp files; Slack-style webhook stub (echoto a log) on success/failure. ✓ Deploy v1 ✔, deploy v2 → automatic rollback ✔, logs tell the whole story without you narrating.
Part C — Challenges (success criteria only)
C1 — Log summarizer. logsum.sh <access.log>: prints total requests, unique IPs, top 5 IPs, top 5 paths, 4xx/5xx counts, busiest hour. Bonus: --top N.
C2 — Parallel pinger. Given servers.txt, check all hosts concurrently (background jobs + wait), print UP/DOWN table, exit non-zero if any down. Compare runtime vs sequential.
C3 — Backup rotator. backup.sh <src> <dest>: timestamped tar.gz, keep newest 7, verify the archive (tar -tzf) before deleting old ones. Cron it on your VM.
C4 — .env validator. Read a .env file; verify required keys (DB_URL, API_KEY, PORT) exist and non-empty; PORT numeric 1–65535; warn on any line without KEY=VALUE shape. Exit codes: 0 ok, 1 invalid, 2 file missing.
C5 — Argument parser. A script supporting -e/--env <name>, -v (verbose flag), -h (usage), positional args after — using a while [[ $# -gt 0 ]] ... case ... shift loop. No getopts shortcuts until you've done it manually once.
C6 — Subshell puzzle. Predict the output BEFORE running:
X=1; (X=2; echo "in: $X"); echo "out: $X"
echo "a b c" | while read -r w _; do FIRST=$w; done; echo "first: ${FIRST:-unset}"Then fix the second so FIRST survives (redirection or process substitution).
Part D — Break & Fix Scenarios
D1 — The unquoted disaster (sandboxed!). In /tmp/dz, create files incl. important.txt, plus a file literally named *. Write a loop that removes files listed in a variable WITHOUT quotes — watch (in dry-run echo mode!) how * expands. Fix with quoting. Write the moral in one sentence at the top of the script.
D2 — The missing set -e. Take Lab 4's deploy, remove set -e, and make the download/copy step fail — observe it "successfully" deploying garbage. Restore set -e.
D3 — Cron amnesia. Put a script using a bare docker or aws command into cron — it fails there but works interactively. Diagnose via captured stderr; fix with absolute paths / explicit PATH. (This is a real-world rite of passage.)
D4 — ShellCheck dojo. Paste this into a file and fix every warning, understanding each:
#!/bin/bash
FILES=`ls /tmp`
for f in $FILES; do
if [ $f == "important" ]; then
cat /tmp/$f | grep error > /dev/null
if [ $? -eq 0 ]; then echo found; fi
fi
done✓ Zero warnings AND you can name the bug each warning prevented.
Part E — Interview Rehearsal (out loud / on a whiteboard)
- What do
set -euo pipefailand quoting protect against? Give a concrete disaster each. - Write (from memory) a retry loop with max attempts and backoff.
- How do you check a file exists and is non-empty? A variable is set and non-empty?
- Why did your variable disappear after a
| while readloop? - When do you stop writing bash and use Python? Name three triggers.
- Live task (common!): "given this log file, print the top 3 error messages with counts" — pipeline it in under 2 minutes.
Done when
every script in B & C is ShellCheck-clean, Lab 4's rollback fires correctly, and you can write C6's fixes and E2's retry loop from memory.
