Every level, in the open
Bash Scripting
19 worlds · 194 levels · 22 bosses
SOLUTION HIDDENTeachers see answer keys in the classroom.
Fourteen worlds of real bash scripts, from your first #! to linted, tested, fleet-wide deploys. Kern hands out missions; hidden tests run your scripts.
Guided levels show the command first. Alone levels give the goal only. Bosses and exams are timed.
Jump to a world
World 1The Forge
11 levelsWhere commands become scripts: your first #!, variables, quotes, $( ), math and read.
Level 1: First spark
Objective: Make ~/forge/spark.sh an executable bash script that prints 'Forge online'.
A script is a text file of commands. Its first line #!/bin/bash says which program runs it, and chmod +x lets you start it as ./name.
Commands taught
shebangLevel 2: Welcome sign
Objective: Write ~/forge/greet.sh so it prints 'Welcome, <HERO>!' using the HERO variable.
A variable is a named box: name=Kern stores (no spaces around =), $name opens it. Kern's sign-maker sets HERO before it runs your script, so inside greet.sh $HERO already holds today's hero.
Commands taught
variablesLevel 3: Name tags
Objective: Write ~/forge/label.sh: create a file named exactly $TARGET and print 'Labelled: <TARGET>'.
Unquoted $var gets split on spaces and its * expanded into file names. Wrap it in double quotes, "$var", and it stays exactly one thing.
Commands taught
quotingLevel 4: Hand it down
Objective: Write ~/forge/paint.sh: copy $PAINT into a variable SHADE, then run the helper ~/forge/show.sh so that it prints 'Painted: <PAINT>'.
A plain variable lives only inside its own script. export NAME hands a copy to every program the script starts. The sign-maker sets PAINT before running paint.sh, and the helper ~/forge/show.sh prints whatever SHADE it can see.
Commands taught
environmentLevel 5: Toolbox
Objective: Try each new tool once, exactly as Kern shows it.
Arrays keep many values under one name, globs can match nothing, and date can print any format. See each one, then type it.
Commands taught
shoptLevel 6: Headcount
Objective: Write ~/forge/count.sh: print 'Items: N' (how many things are in the current directory, 0 if empty) and 'Day: <date +%F>'.
$(command) drops a command's output into your line: day=$(date +%F). Don't count with ls (a name with a newline looks like two): files=(*) makes a list and ${#files[@]} is its length, with shopt -s nullglob above so an empty folder counts 0.
Commands taught
command-substitutionLevel 7: Quick math
Objective: Try math, read and unset once, exactly as Kern shows them.
Bash does whole-number math inside $(( )), reads a line into a variable with read, and forgets one with unset. Type each one and watch.
Level 8: Damage report
Objective: Write ~/forge/damage.sh: print 'HP left: X' where X = HP - DMG * HITS.
$(( )) does integer math: $((HP - DMG * 2)). Inside it you can drop the $ on variable names.
Commands taught
arithmeticLevel 9: Who goes there?
Objective: Write ~/forge/ask.sh: read one line (a name) from stdin and print 'Hello, <name>.'.
read -r name takes one line from the input and stores it in name. The -r keeps backslashes as typed.
Commands taught
readLevel 10: Burn after reading
Objective: Write ~/forge/burn.sh: print 'token: <TOKEN>', then unset TOKEN, then run ~/forge/peek.sh.
unset NAME removes a variable completely, unlike NAME= (still there, just empty), so programs you start afterwards don't inherit it. The caller sets TOKEN; ~/forge/peek.sh reports what it can see.
Level 11: BOSS: The receipt
Objective: Make ~/forge/receipt.sh executable: read item, then qty, from stdin; print 'Date: <date +%F>', 'Item: <item>', 'Total: <qty × PRICE>'.
The Forge opens for business, and every sale needs a receipt: shebang, variables, quotes, $( ), $(( )) and read, all in one. PRICE arrives from outside like HERO did, and the date is whatever date +%F prints.
World 2The Gate
10 levelsWhere scripts learn to decide: if, tests, [[ ]], case and logic.
Level 12: The key
Objective: Write ~/gate/door.sh: print OPEN if a file named $KEY exists in the current directory, else LOCKED.
if COMMAND; then …; else …; fi runs a branch depending on success. [ -f "$f" ] is the command that tests 'is this a file?'.
Commands taught
if-testLevel 13: Test bench
Objective: Ask each test once, exactly as Kern shows it.
A test is a yes/no question, answered by its exit status; && echo only speaks when the answer is yes. Ask each one once.
Level 14: Veterans only
Objective: Write ~/gate/rank.sh: print VETERAN if $LEVEL is 10 or more, else ROOKIE.
Numbers need number tests: -eq -ne -lt -le -gt -ge, as in [ "$n" -ge 10 ]. A > sign compares text like a dictionary instead (inside [[ ]], the test you meet next), so there 9 sorts after 10.
Commands taught
numeric-testsLevel 15: Badge check
Objective: Write ~/gate/badge.sh: print VALID if $BADGE looks like ABC-1234 (3 capitals, dash, 4 digits), else INVALID.
[[ ]] is bash's smarter test: no word splitting, == takes glob patterns and =~ takes a regex (a pattern: ^ is the start, $ the end, [0-9] one digit, {4} exactly four of the thing before it). [[ $id =~ ^[0-9]+$ ]] means 'only digits'. Never put quotes around the regex.
Commands taught
double-bracketsLevel 16: Dictionary order
Objective: Write ~/gate/order.sh for $A and $B: identical text → SAME, otherwise print '<the one that sorts first as text> first'.
Inside [[ ]], != is true when two texts differ, and < or > compare them as text, like a dictionary: 10 comes before 9, because 1 comes before 9. Quote the right side of == and != so it counts as plain text, not a pattern.
Level 17: The lever
Objective: Write ~/gate/lever.sh for $CMD: open → Opening, close → Closing, status → STATUS: ok, anything else → unknown: <CMD>.
case matches one value against patterns, top to bottom: open) …;; close) …;; *) catches everything else.
Commands taught
caseLevel 18: Supply drop
Objective: Write ~/gate/drop.sh: $DEST is a writable directory → READY; doesn't exist → MISSING; anything else → BLOCKED.
Join tests with && (and), || (or), and flip one with !. [[ -d $d && -w $d ]] means 'a directory I can write to'.
Commands taught
logical-operatorsLevel 19: Take it apart
Objective: Write ~/gate/version.sh for $VER like v1.2.3: print 'major 1', 'minor 2', 'patch 3' (each on its own line); anything else → 'not a version'.
Put (parentheses) around parts of a regex and, after a successful [[ x =~ re ]], bash fills the array BASH_REMATCH: [0] is the whole match, [1] the first group, [2] the second. Keep the regex in a variable (re='…') and use [[ $x =~ $re ]].
Level 20: Triage
Objective: Write ~/gate/triage.sh for $F: MISSING, DIR, EMPTY (0 bytes), BIG (over 100 lines) or SMALL.
Wounded files arrive at the Gate. Sort them fast: chain elif tests from the most specific question down.
Level 21: BOSS: The gatekeeper
Objective: ~/gate/keeper.sh: empty $NAME or $PIN not 4 digits → DENIED; admin → ADMIN; guard-* → GUARD; others → VISITOR if PIN ≥ 5000, else DENIED.
The Gate needs a real gatekeeper program. Strings, numbers, regex, case and logic: one script decides who walks in.
World 3The Mill
12 levelsWhere one job happens a thousand times: for, globs, ${f%.ext}, while read, break and continue.
Level 22: Countdown
Objective: Write ~/mill/countdown.sh: count down from $N to 1, one number per line, then print Liftoff.
A loop repeats commands. for ((i=5; i>=1; i--)); do …; done counts like a clock: start at 5, keep going while i>=1, and i-- takes 1 off after each round.
Commands taught
for-loopsLevel 23: Wait for it
Objective: Write ~/mill/wait.sh: until the file ./ready exists, print 'waiting' and sleep 1; then print 'go'.
until is while upside down: until COMMAND; do …; done keeps looping as long as the command FAILS, and stops the moment it succeeds. It tests first, so if the thing is already there the loop body never runs.
Commands taught
until-loopsLevel 24: Roll call
Objective: Write ~/mill/list.sh: print the name of every .txt file in the current directory, one per line.
for f in *.txt loops over matching file names, one at a time, even names with spaces. Keep "$f" quoted inside the loop.
Commands taught
globbingLevel 25: Empty-handed
Objective: Write ~/mill/zips.sh: print the name of each .zip file, one per line, then 'total: N' (0 when there are none).
When nothing matches, a glob stays as the literal text: for f in *.zip runs once with f=*.zip. shopt -s nullglob turns it into 'no names at all', so the loop correctly runs zero times.
Level 26: Strip the tags
Objective: Write ~/mill/names.sh: for every .log file in the current directory, print its name without .log.
${f%.log} is $f with .log cut off the end; ${f#*/} cuts from the start. Bash trims names without calling any tool.
Commands taught
param-expansionLevel 27: Loop yard
Objective: Try seq, while read, continue and break once, exactly as Kern shows them.
seq makes numbers to feed a loop, while read walks lines, continue skips a turn and break stops the loop. Type each one.
Commands taught
seqLevel 28: Tally
Objective: Write ~/mill/sum.sh: read numbers from stdin, one per line, and print their total.
while read -r line; do …; done repeats once per input line until the input ends. Add < file after done to read a file instead of stdin.
Commands taught
while-readseqLevel 29: The sieve
Objective: Write ~/mill/sieve.sh: echo stdin lines, but skip empty lines and lines starting with #, and stop at a line END.
continue skips to the next round of a loop; break leaves the loop for good.
Commands taught
break-continueLevel 30: Dash names
Objective: Write ~/mill/sweep.sh: delete every regular file here (folders stay; some files are named -rf and -i), then print 'swept N'.
A file called -rf, expanded by a bare *, turns into an option: rm * becomes rm -rf …. Start the glob with ./ (./*) so every name begins with ./, and put -- before names to say 'options end here'.
Level 31: The vanishing count
Objective: Fix ~/mill/errors.sh, which always prints 'errors: 0': keep the '! <line>' lines and end with the real 'errors: N' for the ERROR lines of mill.log.
cmd | while read … runs the loop in a subshell (a copy of the shell), so variables it changes vanish after done. Feed the loop with done < <(cmd) instead and it runs in your own shell.
Level 32: Photo flood
Objective: Write ~/mill/rename.sh (renames every *.jpeg in the current dir to .jpg) and run it in ~/mill/photos.
200 photos landed in ~/mill/photos as .jpeg and the archive only takes .jpg. Nobody renames 200 files by hand.
Level 33: BOSS: The mill report
Objective: ~/mill/report.sh: per *.log, count lines (skip # lines, stop at the line EOF) and print '<name>: <n> <n stars>'; no logs → 'no logs'.
Every machine in the Mill keeps a .log. The foreman wants one line per machine: its name without .log, its count, and a bar of that many stars (grow a string in a loop: bar="$bar*").
World 4The Armory
12 levelsWhere scripts become tools: functions, return codes, local, arrays and maps.
Level 34: The hammer
Objective: In ~/armory/tools.sh, define a function double that prints twice its number (double 21 → 42).
name() { …; } defines your own command. Inside, $1 is the first thing passed to it: double 21 → $1 is 21.
Commands taught
functionsLevel 35: Even or odd
Objective: In ~/armory/tools2.sh, define is_even N: return 0 if N is even, 1 if odd, and print nothing.
A function answers yes/no with return: return 0 means success (yes), return 1 means failure (no). if is_even 4; then … uses that answer.
Commands taught
returnLevel 36: The side room
Objective: Write ~/armory/sub.sh: print 'inside: <pwd>' from ( cd /tmp … ), then 'outside: <pwd>' (unchanged), then run { cd /tmp; } and print 'after group: <pwd>'.
( commands ) runs in a subshell, a copy of the shell: a cd or a variable change inside never leaks out. { commands; } runs in the current shell (note the spaces and the final ;), so its changes stay.
Commands taught
subshellLevel 37: Weapon rack
Objective: Write ~/armory/rack.sh: mapfile -t the stdin lines into an array, print 'count: N' and 'last: <last line>'.
An array holds many values in one variable: rack=(sword 'big axe'), and ${rack[0]} is the first one (counting starts at 0). mapfile -t rack fills it from input, one line per item.
Commands taught
arraysLevel 38: Tool belt
Objective: Try each tool once, exactly as Kern shows it.
Six small tools for functions and arrays: upper case, local, -n, +=, named arrays and indirect names. See each one, then type it.
Level 39: No leaks
Objective: In ~/armory/tools3.sh, define shout: store its argument in UPPERCASE in a local variable word, then print it with '!'.
Variables set inside a function are global unless you declare them local. local word=… lives only until the function returns.
Commands taught
localLevel 40: Locked box
Objective: Write ~/armory/limits.sh: readonly MAX=3; try MAX=$WANT inside ( ) with errors hidden: ok → 'changed', fails → 'locked'; then print 'MAX=<value>'.
readonly NAME=value (or declare -r NAME=value) makes a variable that can't be changed or unset any more, a good fit for constants. A try to change it fails with an error, which you can catch with if.
Commands taught
readonlyLevel 41: Reverse march
Objective: Write ~/armory/reverse.sh: read lines from stdin into an array and print them in reverse order.
Loop over an array with for x in "${a[@]}" (quotes keep each item whole), or over its indexes with a counting loop.
Level 42: Build the command
Objective: Write ~/armory/finder.sh: grep $PATTERN in ./notes.txt, adding -i if NOCASE is non-empty and -n if NUMBERED is non-empty (the pattern may hold spaces).
To build a command from pieces, don't glue a string together: put each word in an array and run it with "${args[@]}". Every element stays one word, so a pattern with spaces stays one pattern, and an empty array adds nothing at all.
Level 43: Loot count
Objective: Write ~/armory/loot.sh: read one word per line from stdin and print '<word> <times seen>' for each word, sorted by word.
declare -A makes a map from names to values: count[sword]=3. ${!count[@]} lists the keys, ${count[$k]} reads one.
Commands taught
assoc-arraysLevel 44: Is it there?
Objective: Write ~/armory/has.sh: map stock holds sword=3, shield=0, torch=(empty); print 'have' if $KEY is one of its keys, else 'none'.
An empty or zero value is still a value, so to ask 'is this key in the map?' use [[ -v map[key] ]]. Testing the value ([[ -n ${map[key]} ]]) can't tell missing from present-but-empty.
Level 45: BOSS: The quartermaster
Objective: ~/armory/stock.sh: map STOCK, stock_add NAME QTY, stock_get NAME (unknown → return 1), stock_list (add order), stock_total; no leaked globals.
A stock library other scripts can source: stock_add adds QTY to NAME's count, stock_get prints one count, stock_list prints 'NAME QTY' lines in the order names first arrived, stock_total prints the sum.
World 5The Dock
9 levelsWhere scripts take orders: $1, "$@", shift, usage errors and getopts.
Level 46: Signal drill
Objective: Try >&2 and a number check once, exactly as Kern shows them.
Error messages belong on stderr, and a regex can check that a value is a number. See each one, then type it.
Level 47: Hail the ship
Objective: Write ~/dock/hail.sh: hail.sh NAME prints 'Ahoy, NAME!', and with no argument prints 'Ahoy, sailor!'.
Words after a script's name are its arguments: $1 is the first, $2 the second. ${1:-sailor} means 'use $1, or sailor if there is none'.
Commands taught
positional-argsLevel 48: The manifest
Objective: Write ~/dock/manifest.sh: print 'N crates' (N = number of arguments), then each argument on its own line.
$# is how many arguments arrived, and "$@" is all of them, each kept whole. for c in "$@" visits them one by one.
Commands taught
all-argsLevel 49: Knots
Objective: Write ~/dock/join.sh SEP WORD…: join the words with SEP, using shift (join.sh - a b c → a-b-c).
shift drops $1 and moves every argument one step left: $2 becomes $1. Grab the first ones, shift them away, loop over the rest.
Commands taught
shiftLevel 50: The signal flag
Objective: Write ~/dock/flag.sh [-c COLOR] with getopts: print 'flag: COLOR', or 'flag: white' when there is no -c.
getopts reads options for you, one per round of a while loop: while getopts 'c:' opt; do case $opt in c) color=$OPTARG ;; esac; done. The : after c means -c takes a value, and getopts hands that value over in $OPTARG.
Commands taught
getoptsLevel 51: Two ropes
Objective: Write ~/dock/tie.sh A B: print 'A <-> B'; with any other number of arguments print a usage line to stderr and exit 2.
A good tool explains itself when used wrong: print a usage line to stderr with >&2 and stop with exit 2, the code for 'wrong usage'.
Commands taught
usageLevel 52: The horn
Objective: Write ~/dock/horn.sh [-n NAME] [-l]: print 'Ahoy, NAME' (default crew), all uppercase with -l; an unknown option exits 2.
Same loop as the flag, two options now: in 'n:l', -n takes a value and -l is a plain switch, and getopts reads -l -n Kern or -ln Kern alike. An option it doesn't know arrives as ?, so a *) branch in the case can exit 2.
Level 53: Cargo weight
Objective: Write ~/dock/sum.sh UNIT N…: print 'TOTAL UNIT'; fewer than 2 args or a non-number → message on stderr, exit 2.
The scale clerk wants a command, not a calculator: a unit, then any number of weights, and loud errors for nonsense.
Level 54: BOSS: The packer
Objective: ~/bin/pack [-v] [-o OUT] FILE…: write '== FILE ==' + content of each file to OUT (default pack.txt); -v prints 'packed N files'; bad usage → stderr, exit 2.
The Dock ships files in bundles. Build the packer as a real command in ~/bin: options, defaults, arguments and usage errors.
World 6The Vault
13 levelsWhere failures are caught: exit codes, guards, set -euo pipefail, traps and signals.
Level 55: The probe
Objective: Write ~/vault/probe.sh: run grep -q "$WORD" vault.txt and print 'grep said N' with its exit status; then print 'found' or 'missing' using an if on grep itself.
Every command ends with an exit status: 0 means success, anything else means a kind of failure. $? holds the status of the last command. You can also ask the question directly: if grep -q "$WORD" file; then … runs the branch on success, no $? needed.
Commands taught
exit-codesLevel 56: Port check
Objective: Write ~/vault/port.sh: $PORT not a number → stderr + exit 3; outside 1–65535 → stderr + exit 4; otherwise exit 0 silently.
exit N ends a script with status N, so callers know what went wrong. A guard checks and bails out in one line: test || { echo 'why' >&2; exit 3; }.
Commands taught
guardsLevel 57: Safety net
Objective: Try each safety tool once, exactly as Kern shows it.
The vault's build tools, a pipe that hides failures, a guard for empty variables and a job in the background. See each one, then type it.
Commands taught
sleepLevel 58: Strict mode
Objective: Write ~/vault/release.sh: print 'release $VERSION', then run forge, temper, ship; stop at the first failure, crash if VERSION is unset.
By default bash keeps going after errors and treats typos as empty. set -e stops at the first failing command; set -u stops on an unset variable.
Commands taught
strict-modeLevel 59: Trapdoor
Objective: Write ~/vault/build.sh (set -e): tmp=$(mktemp), print the path, forge > "$tmp", temper < "$tmp"; a trap on EXIT must always delete the temp file.
trap 'commands' EXIT runs whenever the script ends (success, error or set -e crash), perfect for deleting mktemp files. Use single quotes so $tmp is read when the trap runs, not when you set it.
Commands taught
trapLevel 60: Leaky pipe
Objective: Write ~/vault/count.sh: print 'ingots: N' (forge | wc -l); if forge fails, exit non-zero and print nothing.
A pipeline's status is its LAST command's, so forge | wc -l 'succeeds' even when forge fails. set -o pipefail makes any failing stage fail the whole pipe.
Commands taught
pipefailLevel 61: Every stage
Objective: Write ~/vault/stages.sh: run 'forge | temper > /dev/null' and print 'forge=N temper=M' with each stage's own status.
After a pipeline, $? only describes the LAST stage, but the array PIPESTATUS holds every stage's status (${PIPESTATUS[0]}, ${PIPESTATUS[1]}…). Read it on the very next line, because any command replaces it.
Level 62: One log
Objective: Write ~/vault/nightly.sh: first, exec all output (stdout + stderr, appending) into ./nightly.log; then run: echo start, forge, ls /nope, echo end.
exec with only redirections changes where the REST of the script sends its output: exec >>run.log 2>&1 sends stdout and stderr to run.log (appending) for every command after it. Handy for scripts that run alone.
Commands taught
exec-redirectLevel 63: The mask
Objective: Fix ~/vault/stamp.sh, which prints 'all done' even when forge fails: a failing forge must stop it with a non-zero exit before 'all done'.
local out=$(cmd) hides cmd's failure: local itself succeeds, and its status replaces the command's, so even set -e doesn't notice. Declare first, assign on the next line: local out, then out=$(cmd).
Level 64: Careful purge
Objective: Write ~/vault/purge.sh: empty the folder $DEST (the folder stays); if DEST is unset or empty, delete nothing, print an error on stderr and exit non-zero.
rm -rf "$DEST"/* with an empty DEST becomes rm -rf /*. "${DEST:?}" stops the script with an error if DEST is unset OR empty (set -u only catches unset). Put it in front of every rm -rf that uses a variable.
Level 65: Night watch
Objective: Write ~/vault/watch.sh: print watching, loop forever; on TERM print saving, write saved to state.txt, exit 0.
kill sends TERM, the polite 'please stop'. trap 'commands' TERM lets a script save its work before leaving instead of dying mid-sentence.
Commands taught
sleepLevel 66: Backup guard
Objective: ~/vault/backup.sh SRC DEST: no SRC dir → exit 3; mkdir -p DEST fails → exit 4; cp -r fails → 'copy failed (code N)' + exit 5; else 'backed up N files'.
The nightly backup must say exactly what broke. Guard every step, keep the failing command's own code from $?.
Level 67: BOSS: Release night
Objective: ~/vault/ship.sh: forge "$VERSION" | temper into a mktemp file, ship it; ship fails → exit 5; TERM → 'aborted' on stderr, exit 143; never leak the temp file.
Release night: the Vault ships only perfect builds, then prints 'released VERSION'. Strict mode, pipefail, guards with a message on stderr, a temp file that never leaks, and a clean abort on TERM.
World 7The Press
8 levelsWhere text gets processed: IFS, printf, here-docs, awk, sed -i and pipelines in scripts.
Level 68: Word edges
Objective: Try a sed swap without and with word edges, exactly as Kern shows it.
A plain sed swap also hits the word hiding inside a longer one. \b marks a word edge, so only whole words change.
Level 69: The roster
Objective: Write ~/press/roster.sh: read 'name,hp,class' lines from stdin and print '<name> (<class>) <hp>' for each.
IFS is the list of characters read splits on. IFS=, read -r name hp class splits one CSV line into three variables, just for that read.
Commands taught
ifsLevel 70: The ledger
Objective: Write ~/press/ledger.sh: for each 'item qty' line on stdin, print the item left-aligned in 10 columns, a space, the qty right-aligned in 5.
printf FORMAT ARGS prints exactly what you ask: %s is text, %d a whole number, and %-10s / %5d pad to a width (- means left-aligned).
Commands taught
printfLevel 71: The scroll
Objective: Write ~/press/mkconf.sh: using a here-doc, write app.conf with lines [server], name=$APP, port=$PORT, and the literal motd=Welcome $USER.
A here-doc feeds many lines to a command: cat > file <<EOF, the lines, then EOF alone on a line. Variables inside are filled in; write \$ (or quote 'EOF') to keep a $ as text.
Commands taught
heredocLevel 72: Gold tally
Objective: Write ~/press/gold.sh FILE: print the total of column 3 over lines whose column 2 is gold (0 if none).
awk reads a file line by line and splits each into fields $1 $2 $3. awk '$2 == "gold" { s += $3 } END { print s }' sums a column where a condition holds.
Commands taught
awkLevel 73: Spellcheck
Objective: Write ~/press/fix.sh FILE…: in every file, replace colour → color and the word teh → the, in place, keeping FILE.bak backups.
sed -i edits files in place; sed -i.bak keeps the original as FILE.bak. s/old/new/g replaces every match, and \b marks a word edge.
Commands taught
sed-inplaceLevel 74: Broken links
Objective: Write ~/press/toppaths.sh LOG: for status-404 lines, strip ?query from the path (field 3) and print the 3 most common as 'COUNT PATH'.
The web log has 20,000 lines and readers keep hitting dead pages. Find the worst ones with a pipeline, inside a script.
Level 75: BOSS: The morning edition
Objective: ~/press/report.sh LOG: with title/top from ./report.conf print '== TITLE ==', 'requests: N', 'errors: E (P%)' (status ≥ 500), 'top K IPs:', 'COUNT IP' lines.
The morning report reads the web log (IP METHOD PATH STATUS) and report.conf (title=… and top=… lines). P is whole-number math, errors × 100 / requests, rounded down.
World 8The Tower
10 levelsWhere scripts run on their own: bash -x, classic pitfalls, cron, logging, locks, and the final tool.
Level 76: The trace
Objective: Trace ~/tower/sum.sh with bash -x, find why sum.sh 1 2 3 prints 0+1+2+3, and fix it to print 6.
bash -x script.sh runs a script and prints every command, after expansion, with a + in front. You see what bash really did, not what you meant.
Commands taught
debuggingLevel 77: Line by line
Objective: Find the syntax error in ~/tower/oops.sh with bash -n and fix it: it should print big (N > 10) or small, then 'checked N'.
bash -n script.sh only checks the syntax and runs nothing, and its error names a line number. For a trace with line numbers, set PS4='+ $LINENO: ' before bash -x.
Level 78: Space invaders
Objective: Fix ~/tower/clean.sh DIR so it deletes only the *.tmp files in DIR, even when DIR or the file names contain spaces.
The classic script bugs: $(ls) in a for loop, unquoted $var, paths built without quotes. They work in tests and fail on the first file with a space.
Commands taught
pitfallsLevel 79: Night shift
Objective: Schedule ~/tower/backup.sh every 15 minutes in your crontab, appending its output to ~/tower/backup.log (use full paths).
cron runs commands on a schedule: five fields (minute hour day month weekday), then the command. */15 in the minute field means every 15 minutes.
Commands taught
cronLevel 80: Tower tools
Objective: Try each tower tool once, exactly as Kern shows it.
All the arguments at once, a byte count, a lock, a slice of a string and a read test. See each one, then type it.
Commands taught
flockLevel 81: The logbook
Objective: In ~/tower/log.sh define log LEVEL MSG…: append 'YYYY-MM-DD HH:MM:SS [LEVEL] MSG' to $LOGFILE; ERROR lines also go to stderr.
Scripts that run alone must leave a trail: one line per event with a timestamp and a level. date '+%F %T' gives 2026-11-16 09:30:00.
Commands taught
loggingLevel 82: One at a time
Objective: Write ~/tower/sync.sh: lock /tmp/sync.lock with flock -n (if busy: busy on stderr, exit 1), print syncing, sleep ${NAP:-2}, print done (test: & then wait).
cron doesn't wait: if a run is slow, the next one starts on top of it. exec 9> lockfile opens a file on descriptor 9, and flock -n 9 grabs its lock or fails at once.
Commands taught
flockLevel 83: The haunted script
Objective: Trace ~/tower/rotate.sh with bash -x and fix it: for every non-empty *.log in DIR, move it to *.log.1 and create a new empty one; bad DIR → exit non-zero.
The log rotator works on the dev's laptop and wrecks everything on the Tower. Trace it, find every pitfall, fix it before the logs overflow.
Level 84: Heartbeat
Objective: Make ~/tower/heartbeat.sh executable: flock -n /tmp/heartbeat.lock or exit 1, append '<date +%F %T> beat' to ~/tower/heartbeat.log; cron it every 5 min.
The Tower must prove it's alive every 5 minutes, never twice at once, with a timestamp in a log. Schedule, lock, log: the automation trio.
Level 85: FINAL BOSS: logwatch
Objective: Write ~/bin/logwatch [-q] [-o FILE] LOG…: count [ERROR]/[WARN]/[INFO] lines and report (codex logwatch); exit 1 on errors, 2 on bad usage.
The last job: a real tool for the whole machine. logwatch reads logs, counts levels and reports, with options, strict mode and honest exit codes.
Commands taught
logwatch
World 9Lint Hall
8 levelsWhere scripts get read before they run: ptr-lint findings, ShellCheck codes, and the fixes that keep servers alive.
Level 86: Old ways
Objective: Try each old habit and its tools once, exactly as Kern shows them.
The nightly script is full of old habits: basename, backticks and expr. Meet them here, plus ptr-lint's one-line format and a -h check.
Commands taught
dirname-basenameLevel 87: First finding
Objective: Run ptr-lint on ~/lint/backup.sh and fix what it reports until it comes back clean (the tests back up a file called 'my notes *.txt').
A linter reads a script without running it and points at traps; the real one is ShellCheck, and this VM has its look-alike ptr-lint (same codes, same output). Each finding shows the line, a caret ^ at the spot, a code like SC2086 and a severity: error, warning, info or style.
Commands taught
ptr-lintshellcheck-codesLevel 88: Masked failure
Objective: Fix ~/lint/version.sh so ptr-lint is clean: with no VERSION file it must stop with a non-zero exit, not print 'tagged'.
SC2155 (warning): local v=$(cmd) is one command, and local's own success replaces cmd's failure, so set -e never sees it. ptr-lint flags it; the fix is to declare, then assign: local v, then v=$(cmd).
Level 89: When it fires
Objective: Fix ~/lint/pack.sh (it runs gzip on a temp copy): the temp file must really be deleted when it ends, and ptr-lint is clean.
SC2064 (warning): trap "rm -f $tmp" EXIT builds the command NOW, when tmp may still be empty. Single quotes keep $tmp as text until the trap fires: trap 'rm -f "$tmp"' EXIT.
Level 90: Safe landing
Objective: Fix ~/lint/purge.sh: it must empty $CACHE (with spaces in its name), and fail without deleting anything when CACHE is unset or doesn't exist. ptr-lint clean.
Two warnings that have deleted real servers: SC2164, a cd that fails while the script carries on in the wrong folder (write cd "$d" || exit 1), and SC2115, rm -rf "$DIR"/* turning into rm -rf /* when DIR is empty (write "${DIR:?}"/*).
Level 91: Words aren't lines
Objective: Fix ~/lint/roster.sh: one line per log ('web app.log: 3') and one hello per line of names.txt ('hello, Ada Lovelace'). ptr-lint clean.
SC2045 (error): for f in $(ls) breaks names at spaces; loop over the glob: for f in *.log. SC2013 (info): for x in $(cat file) loops over words, not lines; read lines: while IFS= read -r x; do …; done < file.
Level 92: Old scrolls
Objective: Modernise ~/lint/legacy.sh until ptr-lint finds nothing, printing the same sizes, total and 'over by N' as before.
Old scripts use `cmd` (SC2006), expr (SC2003) and [ $a -gt $b ]: they still run, but backticks don't nest and expr is a whole extra program. Modern bash says $(cmd), $(( a + b )) and (( a > b )).
Commands taught
legacy-syntaxLevel 93: BOSS: Zero findings
Objective: Bring ~/lint/nightly.sh to zero ptr-lint findings in four passes, with backups that still work on folders with spaces and never delete outside DEST.
A real job: the nightly backup script works on the dev box and nobody dares touch it. Lint it, fix it in passes (quoting, then the dangerous ones, then the old syntax) and keep it working after every pass.
World 10Style Wing
8 levelsScripts other people can read: headers, main, constants, shfmt, reviewing generated code, and knowing when to stop.
Level 94: Name plate
Objective: Give ~/style/rename.sh a header (line 2: # rename.sh - …, plus a # Usage: line), a comment above the function, and make rename.sh -h print the usage.
Line 2 says what the script is (# name.sh - what it does), a # Usage: line says how to call it, and every function gets a one-line comment above it. Scripts are read far more often than written, and Google's shell style guide asks for exactly this.
Commands taught
script-headerLevel 95: String tricks
Objective: Try each string trick once, exactly as Kern shows it.
Bash can swap or cut parts of a variable without sed, and ! flips a test. See each one, then type it.
Level 96: Main gate
Objective: Restructure ~/style/slug.sh: slugify (one title → slug), the loop in main with locals, main "$@" last; sourcing it runs nothing.
Put all the work in functions, and a main function that runs them; the last line calls main "$@". With if [[ ${BASH_SOURCE[0]} == "$0" ]]; then main "$@"; fi the file can also be sourced, by a test or another script, without running anything.
Commands taught
main-functionLevel 97: One name, one number
Objective: ~/style/quota.sh counts the wrong files: give the limit one readonly UPPER_CASE name at the top and use it in the test, the message and the count.
A number that appears three times will be changed in two, so name it once at the top: readonly LIMIT_KB=100. Constants and exported variables go in UPPER_CASE, everything else in lower_snake_case, and readonly turns any later change into an error.
Commands taught
namingLevel 98: Straight lines
Objective: Format ~/style/messy.sh with shfmt (2-space indents) so hidden shows nothing, and it still counts down.
shfmt formats shell scripts the way gofmt formats Go: same indentation, same spacing, no arguments in review. shfmt -i 2 -d FILE shows what it would change (CI uses that), shfmt -i 2 -w FILE rewrites it.
Commands taught
shfmtLevel 99: The AI wrote this
Objective: ~/style/prune.sh was generated and has six bugs: make it do exactly what its header says, with zero ptr-lint findings.
Generated code looks confident, so review it like a colleague's: run the linter, then test every edge case the header promises. A clean ptr-lint only means no known patterns; logic bugs (an unanchored regex, a flag that does nothing, an off-by-one) need tests and reading.
Commands taught
code-reviewLevel 100: The right tool
Objective: Read the six cards in ~/style/cards and write ~/style/verdict.txt with one line per card: '1 bash' or '1 python'.
Bash is glue: run programs, check their exit codes, move files. Google's style guide says that past about 100 lines, or once you need real data structures, you rewrite in a structured language, and knowing when to stop is part of writing bash well.
Commands taught
when-not-bashLevel 101: BOSS: Clean room
Objective: Write ~/style/deploy-v2.sh from scratch, doing what the header of ~/style/deploy.sh promises: clean style, zero ptr-lint findings, shfmt-clean.
deploy.sh is the messiest script on the server and it lies: its dry run still writes .bak files. Don't patch it; rewrite it from its header, in clean style, one checked piece at a time.
World 11Proving Ground
13 levelsWhere scripts earn trust: golden files, assert helpers, bats tests, test doubles, CI, and a hunt for mutants.
Level 102: Assert tour
Objective: Try loading a helper file and calling it once, exactly as Kern shows it.
A test file loads helper functions with a dot, then calls them. See each one, then type it.
Level 103: Golden output
Objective: Write ~/proving/test-greet.sh: compare ./greet.sh Ada's output with expected/greet-ada.txt; exit 0 on a match, else show the difference and fail.
A golden test runs the code and compares its whole output with a saved, known-good copy. diff <(cmd) file does it in one line: silent and exit 0 when equal, the differing lines and exit 1 when not.
Commands taught
diffLevel 104: Say it plainly
Objective: Write ~/proving/assert.sh: assert_eq EXP ACT [LABEL] prints 'ok - LABEL' (return 0) or "not ok - LABEL: expected 'EXP', got 'ACT'" on stderr (return 1).
An assert helper turns a comparison into a clear verdict: ok, or exactly what was expected and what came instead. It returns 1 on failure, never exits, so the rest of the tests still run.
Commands taught
assert-helpersLevel 105: First @test
Objective: Write ~/proving/tests/add.bats with at least two @test blocks that check ./add.sh on two different pairs of numbers, then run hidden.
bats runs .bats files: each @test "name" { … } block is a test, and it fails as soon as one line in it fails. One example can be faked; two can't.
Commands taught
batsLevel 106: Fail loudly
Objective: Make ~/proving/build.sh stop at the first failing stage (even compile | tee) and print 'build failed at line N' on stderr, N = the failing line.
A script under test must fail loudly: set -euo pipefail stops at the first error (also inside a pipe), and trap '…' ERR runs right before it stops. In single quotes, $LINENO is read when the trap fires: the line that broke.
Commands taught
err-trapLevel 107: Run, then judge
Objective: Write ~/proving/tests/port.bats (3+ tests using run, $status, $output): 'ok PORT' + exit 0 for 1–65535, exit 1 outside, exit 2 for a non-number.
run CMD executes CMD inside a test without failing it, and keeps the exit code in $status and the output in $output. Then you check them, and you check the edges: 0, 1, 65535, 65536.
Commands taught
bats-runLevel 108: Clean bench
Objective: Write ~/proving/tests/backup.bats (2+ tests) for backup.sh SRC DEST: setup() builds a temp source, teardown() removes it, nothing left behind.
setup() runs before every test and teardown() after it, pass or fail. Build a fresh world in a mktemp -d folder, test in it, throw it away: no test sees another's leftovers.
Commands taught
test-fixturesLevel 109: Two streams
Objective: Write ~/proving/tests/convert.bats (2+ tests): convert.sh prints only the number on stdout (100 → 212, 2000 → 3632), its warning only on stderr.
Plain run mixes stdout and stderr into $output. run --separate-stderr keeps them apart: stdout in $output, stderr in $stderr. Data on stdout, chatter on stderr, and a test that proves it.
Commands taught
test-streamsLevel 110: Stand-ins
Objective: Write ~/proving/tests/diskwarn.bats (at least 2 tests) that fakes df (e.g. tests/stubs/df on the front of PATH) so diskwarn.sh sees 95 %, 40 % and exactly 90 %.
You can't fill a real disk to 95 % for a test. A test double is a fake command that says whatever the test needs: put it in a folder at the FRONT of PATH and the script under test finds it first.
Commands taught
test-doublesLevel 111: Edge cases
Objective: Write ~/proving/tests/slug.bats (2+ tests) that pass on slug.sh and catch 2 broken versions: one squeezes double spaces, one accepts empty input (must exit 2).
Bugs hide at the edges: two spaces in a row, an empty argument, digits, symbols. The happy path is the one test everybody writes; the edges are the ones that save you.
Commands taught
edge-casesLevel 112: The one that got away
Objective: Ticket: 'export says 2 orders, there were 3' (no newline at the end); add a test to tests/report.bats that fails on report.sh, then fix report.sh.
A bug report means a test was missing. First write the test that fails the way the ticket says (red), then fix the code (green): the bug can never come back unnoticed.
Commands taught
regression-testsLevel 113: One button
Objective: Write ~/proving/ci.sh: '== lint' + ptr-lint ./*.sh, '== test' + bats tests/; red step → 'FAILED: <step>' on stderr, exit 1; green → PASSED (try: ci-demo/).
CI runs the same checks on every push: lint, then tests, and the first red step stops the run with a non-zero exit. A step() function that runs "$@" keeps each stage one line long.
Commands taught
ci-scriptLevel 114: BOSS: Mutant hunt
Objective: Write bats tests in ~/proving/tests/ for levels.sh (counts INFO/WARN/ERROR, exits 2/1/0, 3 on bad usage) that pass on the real script and kill all 5 mutants.
A test suite is only as good as the bugs it catches. Five broken copies of levels.sh are waiting; your tests/levels.bats must pass on the real one and fail on every mutant.
World 12The Wire
10 levelsWhere scripts talk to servers: jq for JSON, curl for HTTP, honest status codes, retries with backoff and paged APIs.
Level 115: jq ladder
Objective: Climb the jq ladder one filter at a time, exactly as Kern shows it.
jq reads JSON one small filter at a time: count, pick an item, unpack, keep, compare, build. users.json is ready.
Level 116: The label
Objective: Write ~/wire/port.sh FILE: print the .port of the JSON file $1, then its .db.port, one per line.
JSON is how programs talk to each other now. jq is grep and sed for JSON: jq '.port' file prints one field, jq '.db.port' digs into a nested object, and jq . pretty-prints the lot.
Commands taught
jqLevel 117: Strings attached
Objective: Write ~/wire/names.sh FILE: print every user's .name raw, one per line, then 'total N' (N = how many users).
Strings come out of jq as JSON, with their "quotes". jq -r prints them raw, ready for bash. .[] walks every element of an array, so .[].name is every name, and length counts the elements.
Level 118: The filter
Objective: Write ~/wire/admins.sh FILE: print the email of every ACTIVE admin in the users file $1, raw, one per line.
select(COND) keeps only the elements where COND is true: .[] | select(.role == "admin"). Join conditions with and / or, and keep piping: | .email takes one field of what's left.
Level 119: Safe envelope
Objective: Write ~/wire/event.sh USER MSG LEVEL: print one JSON object {"user":USER,"msg":MSG,"level":LEVEL}, with LEVEL as a number.
Never glue JSON together with echo: one quote or backslash in the data and it breaks. jq -n builds JSON from nothing: --arg name VALUE passes a string, --argjson n 5 passes a number, and jq does all the escaping.
Level 120: First call
Objective: Write ~/wire/who.sh ID: ask http://api.wire/users/ID and print 'NAME <EMAIL>' for that user.
curl URL fetches a URL and prints the body; -s hides the progress meter. Pipe it into jq and you have an API client. jq can build text too: "\(.name) <\(.email)>" drops the fields into a string.
Commands taught
curlLevel 121: curl ladder
Objective: Climb the curl ladder one flag at a time, exactly as Kern shows it.
Scripts talk to APIs with curl, and the flags decide what you keep: the body, the status, or a clean failure. The API at api.wire is up.
Level 122: Status line
Objective: Write ~/wire/fetch.sh PATH: save http://api.wire/PATH to ./out.json; on a non-2xx answer print 'HTTP CODE' to stderr, delete out.json, exit 1.
curl is happy whenever a server answers, even with 404 or 500: exit 0, error page printed. -o FILE saves the body, -w '%{http_code}' prints the status code. When you only need yes or no, -f turns any HTTP error into exit 22.
Level 123: Try, try again
Objective: Write ~/wire/token.sh: print the .token from http://api.wire/flaky; at most 3 tries (curl -f, --max-time 2), waiting 1 s then 2 s; give up → stderr, exit 1.
Networks hiccup and come back. Retry, but politely: wait between tries and double the wait each time (backoff), give up after a few, and never wait forever: curl --max-time 2 cuts off a hung request.
Commands taught
retriesLevel 124: BOSS: The long list
Objective: Build ~/wire/sync.sh step by step: walk every page of http://api.wire/users?page=N, retry failed pages, print the active users and a JSON summary.
The Wire's directory is too big for one answer: it comes in pages, and the server drops a page now and then. Walk every page, survive the drops, and report.
Commands taught
pagination
World 13The Relay
10 levelsWhere data is passed along: NUL-safe xargs, parallel runs, date math, real CSV, health checks, webhooks and a sync plan.
Level 125: Null and safe
Objective: Write ~/relay/pack.sh DIR: gzip every *.log file under DIR, at any depth and whatever its name, and nothing else.
xargs turns lines into arguments: find … | xargs gzip zips many files at once. But names can hold spaces, quotes, even newlines. find -print0 ends each name with a NUL byte (the one byte a name can't hold), xargs -0 splits on it, -r skips an empty run.
Commands taught
xargsLevel 126: How old?
Objective: Write ~/relay/stale.sh FILE DAYS: FILE has 'HOST YYYY-MM-DD' lines; print the hosts last seen more than DAYS full days before $NOW (a date; default now).
Dates are hard to subtract; seconds are easy. date -d 2026-11-01 +%s turns a date into epoch seconds (counted from 1970). Subtract two and divide by 86400 to get days. date -d also understands '7 days ago' and '@1767225600'.
Commands taught
date-mathLevel 127: awk ladder
Objective: Climb the awk ladder one piece at a time, exactly as Kern shows it.
awk splits each line into fields and runs a tiny program on them. One piece at a time: -F, BEGIN, -v, NR, for, gsub and gawk.
Level 128: Field day
Objective: Write ~/relay/users2csv.sh FILE: from a passwd-format FILE print the header user,uid,shell, then user,uid,shell for every uid from 1000 to 59999.
awk splits each line into fields on FS (-F:) and joins the fields you print with OFS (-v OFS=,): the commas in print $1, $3 become OFS. BEGIN { … } runs before the first line, the place for a header.
Commands taught
awk-fieldsLevel 129: Relay tools
Objective: Try each relay tool once, exactly as Kern shows it.
Clear variable edges, a POST with a body, timing, xargs in parallel and a != test. See each one, then type it.
Level 130: Pulse
Objective: Write ~/relay/check_api.sh for http://api.wire/health (2 s max): OK 0, WARNING 1 (degraded or ≥ $WARN ms, else 500), CRITICAL 2 (down or ≥ 1000 ms), UNKNOWN 3.
Monitoring tools (Nagios, Icinga, Zabbix, Sensu) run tiny check scripts and read the exit code: 0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN, with one line of text starting with that word. A check must answer fast, even when what it checks hangs.
Commands taught
health-checksLevel 131: Ring the bell
Objective: Write ~/relay/alert.sh LEVEL TEXT: POST {"level":LEVEL,"text":TEXT,"host":$(hostname)} as JSON to http://api.wire/hooks; webhook fails → stderr, exit 1.
A webhook is a URL that takes a POST: chat rooms, pagers and CI all accept alerts that way. curl -X POST -H 'Content-Type: application/json' -d "$json" URL sends one. Build the JSON with jq -n, and use -f so a refused alert is an error, not a shrug.
Commands taught
webhooksLevel 132: Many hands
Objective: Write ~/relay/ping-all.sh: run probe HOST for every host in ./hosts.txt, at most 4 at a time, and print all their output.
Eight one-second probes take eight seconds in a loop. xargs -P 4 runs up to four at once, and -n 1 hands each run one argument. By hand it's & and wait, but then you must cap the count yourself.
Level 133: Stale jobs
Objective: Write ~/relay/stale-jobs.sh CSV DAYS: for each job (after the header) last run more than DAYS full days before $NOW, print 'JOB (OWNER): N days', no quotes.
Real CSV quotes any field with a comma inside: "Doe, Jane". Split on commas and you cut her in half. gawk -v FPAT='([^,]*)|("[^"]*")' describes a field instead (comma-free text, or one quoted string); gsub(/"/, "", $i) then strips the quotes.
Level 134: BOSS: api-sync
Objective: Build ~/relay/plan.sh step by step: compare http://api.wire/users with ./users.local.json and print a change plan, with exit codes 0/1/2 and a webhook.
Payroll keeps its own copy of the user list, and it drifts. Before anyone touches it, ops wants a plan: who is new, who left, who changed, who went idle, and a ping when there is work.
Commands taught
api-sync
World 14The Fleet
9 levelsMany machines, one script: ssh in loops, remote scripts, idempotent edits, install, dry runs, fan-out.
Level 135: Roll call
Objective: Write ~/fleet/who.sh HOST: run hostname on HOST over ssh and print 'HOST -> <its answer>'; if ssh fails, exit with its status.
ssh HOST CMD runs CMD on another machine and brings home its output and its exit status, like a local command. name=$(ssh web1 hostname) catches what web1 says about itself.
Commands taught
ssh-remoteLevel 136: Fleet tools
Objective: Try each fleet tool once, exactly as Kern shows it.
Fleet scripts need a few new pieces: ssh in a loop, a script over ssh, an optional character in a regex, sed -E, install -D and --dry-run. See each one, then type it.
Level 137: The hosts file
Objective: Write ~/fleet/check.sh FILE: per host in FILE (skip blanks, # lines) print 'HOST up' if timeout 3 ssh -n HOST true works, else 'HOST DOWN'; any down → exit 1.
Looping over hosts has two traps. ssh reads stdin, so inside while read it swallows the rest of the hosts file: use ssh -n. And a frozen host hangs ssh forever: timeout 3 ssh … gives up after 3 seconds.
Level 138: Carry the script
Objective: Write ~/fleet/report.sh HOST: print 'HOST: N releases, current -> X': N dirs in the host's /srv/app/releases, X the release its /srv/app/current points to.
For more than one command, send a whole script: ssh HOST bash -s <<'EOF', the lines, then EOF. Quote the EOF so the $ parts reach the host untouched; unquoted, your shell expands them here first, on the wrong machine.
Level 139: Say it once
Objective: Write ~/fleet/harden.sh FILE: make sure FILE has the lines 'PermitRootLogin no' and 'PasswordAuthentication no', each exactly once; ten runs = the same file.
Idempotent: running it twice changes nothing the second time. grep -qxF 'LINE' file || echo 'LINE' >> file adds a line only if that exact whole line is missing (-x whole line, -F no regex).
Commands taught
idempotencyLevel 140: Set, don't stack
Objective: Write ~/fleet/setport.sh FILE PORT: Port (or #Port) line becomes 'Port <PORT>', append if none; FILE.bak only when something changes; bad PORT → stderr, exit 2.
Appending isn't enough when a setting already exists: change it in place. Check first (already right → exit 0), back up only before a real change, edit with sed, then verify with grep -qx.
Level 141: One move
Objective: Write ~/fleet/place.sh: install ./app.conf as $DEST/etc/app/app.conf (mode 640) and ./run.sh as $DEST/bin/run (mode 755), creating the folders.
install copies a file and sets its mode in one step: install -D -m 640 src dest also creates missing folders. cp then chmod leaves a moment with the wrong mode, and cp over an existing file keeps that file's old mode.
Commands taught
installLevel 142: Rehearsal
Objective: Write ~/fleet/prune.sh [--dry-run] DIR: delete the *.old files in DIR; with --dry-run print one line per file it would delete and delete nothing.
A --dry-run flag prints what the script would change and changes nothing. Send every change through one helper: run() { if (( dry )); then echo "would: $*"; else "$@"; fi; }.
Commands taught
dry-runLevel 143: BOSS: Fan-out
Objective: Write ~/fleet/push.sh [--dry-run] FILE: FILE → /srv/etc/app.conf (640) on every host in hosts.txt, in parallel, idempotent, 3 s per host; failures → exit 1.
One config file, a whole fleet, some hosts frozen. Compare before you change, change with install, never wait on a dead host, and rehearse with --dry-run.
Commands taught
fan-out
World 15The Harbor
10 levelsWhere releases ship: confirmations, secrets, .env files, symlink switches, health checks, rollbacks, onboarding.
Level 144: Harbor keys
Objective: Try vaultctl and readlink once, exactly as Kern shows them.
Harbor's vault client takes its token on stdin, never as an argument, and releases are symlinks you can read back. See each one, then type it.
Commands taught
readlinkLevel 145: Are you sure?
Objective: Write ~/harbor/wipe.sh [--yes] DIR: empty DIR. --yes → just do it; on a terminal → ask 'wipe DIR? [y/N]'; no terminal and no --yes → stderr + exit 1.
Ask before destroying, but never hang under cron: [ -t 0 ] is true only when stdin is a terminal. Automation passes --yes; with no terminal and no --yes, refuse.
Commands taught
confirm-promptsLevel 146: Loose lips
Objective: Write ~/harbor/login.sh: vaultctl login with the token in $TOKEN_FILE (never on the command line); its output → $SESSION_FILE, mode 600 (even over an old one).
Secrets leak three ways: on the command line (ps shows every argument to every user), in files made with the default umask (644, anyone reads), and in echo or set -x. Feed them on stdin, create files under umask 077.
Commands taught
secretsLevel 147: Data, not code
Objective: Write ~/harbor/loadenv.sh FILE CMD…: export every valid KEY=VALUE line of FILE (skip comments, blanks; bad keys → stderr), never run its values, then run CMD.
source app.env runs the file as bash: a value like $(rm -rf ~) executes. Read it as data: while IFS='=' read -r key value, keep keys matching ^[A-Z_][A-Z0-9_]*$, then export "$key=$value".
Commands taught
env-filesLevel 148: The switch
Objective: Write ~/harbor/release.sh SRC ID: copy SRC to $APP/releases/ID (APP defaults to ~/harbor/app), point $APP/current at it; ID exists → refuse, exit 1.
Deploy into a new folder releases/ID, then flip one symlink: ln -sfn releases/ID current. Without -n, ln -sf on a link to a directory creates the new link INSIDE that directory.
Commands taught
releases-symlinkLevel 149: Is it alive?
Objective: Write ~/harbor/verify.sh: get $URL (default :8088/health) up to $TRIES (5) times, 1 s apart; body ok → print healthy, exit 0; else unhealthy on stderr + exit 1.
A deploy isn't done until the app answers. curl -fsS --max-time 2 URL fails on HTTP errors and slow servers; retry a few times, a second apart, because apps take a moment to start.
Commands taught
deploy-healthLevel 150: The way back
Objective: Write ~/harbor/deploy.sh SRC ID: release SRC as ID, check $URL (default :8088/current/health, $TRIES checks); unhealthy → current back to the old one, exit 1.
Every deploy needs a way back. Remember where current pointed before the switch; if the new release fails its health check, point current back and say so.
Commands taught
rollbackreadlinkLevel 151: New hands
Objective: Try each onboarding tool once, exactly as Kern shows it (you have sudo here).
Onboarding needs random passwords, users made with a real name and passwords set through stdin. See each piece, then type it.
Commands taught
base64onboardingLevel 152: New crew
Objective: Write ~/harbor/onboard.sh CSV (sudo): login,name,group lines; create missing groups/users with random passwords; end with 'created N, existing M, skipped K'.
Onboarding from a CSV must be safe to re-run: create the group if missing, the user if missing, and leave existing ones alone. Passwords go in through chpasswd's stdin and out to a 600 file, never on a command line.
Commands taught
onboardingLevel 153: BOSS: Deploy day
Objective: Write ~/harbor/deploy.sh [--yes] ID: ship ./build to every host in deploy.env as /srv/app/releases/ID, switch, health-check, and roll all hosts back on failure.
A deploy across the fleet: safe settings, a confirmation gate, release folders, one symlink flip per host, a health check, and a way back for everyone.
World 16Old Roads
10 levelsWhere shells start and scripts travel: startup files, PATH, aliases, bashisms, CRLF, old idioms, printf, and one script that runs the same everywhere.
Level 154: Who reads what?
Objective: In the practice HOME ~/roads/home, make .bash_profile echo 'profile' and then load .bashrc, and make .bashrc echo 'bashrc'.
bash reads different startup files depending on how it starts: a login shell reads ~/.bash_profile (or ~/.profile), an interactive terminal tab reads ~/.bashrc, and a plain bash -c script reads neither. An echo in each file makes the order visible.
Commands taught
login-shellsprofile-filesLevel 155: A road for ~/bin
Objective: In ~/roads/home/.bashrc put $HOME/bin on PATH (once only), so 'hello' runs in a login shell and in a new tab.
Programs in ~/bin run by name only when ~/bin is on PATH. Put the line in .bashrc, which new tabs read and the login profile loads, and guard it: sourcing the file twice must not stack duplicates.
Commands taught
path-varlogin-shellsLevel 156: Aliases stay home
Objective: report.sh fails with 'll: command not found'. Replace its alias with a function ll so it prints the number of entries in the directory it is given.
An alias is a typing shortcut: bash expands it only in an interactive shell. A script never sees it. A function works everywhere, takes its arguments properly and can live inside the script.
Commands taught
aliasfunctionsLevel 157: Spot the bashism
Objective: greet.sh starts with #!/bin/sh but uses bashisms: fix every one so it is valid sh and prints exactly the same.
#!/bin/sh promises plain POSIX sh: on Alpine that is busybox ash, on Debian dash. They do not know [[ ]], == inside [ ], or source. 'It ran on my machine' proves nothing: the scan has to be by eye (or by tool).
Commands taught
posix-shbashismsLevel 158: Port it to sh
Objective: inventory.bash uses an array, [[ =~ ]] and ${name^^}: write ~/roads/inventory.sh, a #!/bin/sh version that prints exactly the same.
Porting bash to POSIX sh means replacing features, not deleting them: an array becomes a temp file or a newline list, [[ =~ ]] becomes a case pattern, ${v^^} becomes tr. Most other lines carry over unchanged.
Commands taught
posix-shbashismssort-fieldsLevel 159: Ask for bash by name
Objective: colors.sh uses declare -A but says #!/bin/sh: use #!/usr/bin/env bash, make it executable, and exit 3 with a message unless it runs in bash 4+.
#!/bin/bash assumes bash lives in /bin; #!/usr/bin/env bash finds it on PATH (macOS, NixOS, BSD). A script that needs bash should say so, and stop with a clear message when sh or an old bash runs it: check BASH_VERSION and BASH_VERSINFO before the first bash-only line.
Commands taught
env-shebangLevel 160: The invisible ^M
Objective: Write ~/roads/fixcr.sh FILE...: strip CRLF endings in place, skip clean files, keep modes, report missing files (exit 1), no arguments: usage, exit 2.
A script saved with Windows line endings (CRLF) has a hidden \r at the end of every line, even the shebang: the kernel looks for an interpreter called 'bash\r' and answers 'bad interpreter'. Strip only the \r that ends a line: sed -i 's/\r$//'.
Commands taught
crlfsed-inplaceLevel 161: Read the old scrolls
Objective: Translate legacy.sh into ~/roads/modern.sh (bash): same stdout, stderr and exit code in every case, but no backticks, no expr and no x$1 tricks.
Old scripts are full of idioms from before $( ) and [[ ]]: ${1+"$@"} means pass the arguments (quoted) if there are any; : "${X:=d}" sets X to d when it is empty; [ "x$a" = x ] tests for empty; backticks are $( ); expr does arithmetic and string length.
Commands taught
old-idiomslegacy-syntaxLevel 162: echo is not portable
Objective: banner.sh TEXT must print 'Status: TEXT', a TAB, '[ok]' and a newline for any TEXT, identically under sh and bash. Replace its echo -n / echo -e.
echo differs between shells: -n and -e are not in POSIX, some shells expand backslashes and others do not, and text that looks like a flag (-n) disappears. printf takes a format you control and prints data exactly: printf '%s\n' "$text".
Commands taught
printfposix-shLevel 163: BOSS: Same everywhere
Objective: Write ~/roads/sizes.sh [-s] FILE...: list each file's size, total them, report missing files and directories, and behave identically under sh and bash.
One script, two shells: write for plain POSIX sh (getopts, case, ${f##*/}, printf, mktemp + trap) and it behaves the same on Alpine ash, Debian dash and bash.
Commands taught
sort-fields
World 17On-Call
14 levelsThe pager rings for scripts that broke in production: reproduce like cron, find the cause, fix it, prove it.
Level 164: Dump peek
Objective: Try dbdump and gzip once, exactly as Kern shows them.
dbdump prints a whole database as SQL. Peek at the top with head, and gzip it small. See each one, then type it.
Level 165: The on-call kit
Objective: Save the first 3 lines of dbdump shop in ~/oncall/peek.sql, and the full path of the dbdump command in ~/oncall/where.txt.
Before the pager rings, know your tools. dbdump DB prints a database as SQL lines; head -n 3 shows just the top, and command -v NAME tells you which file runs when you type NAME.
Commands taught
dbdumpLevel 166: Works on my machine
Objective: PAGER: status.log stopped updating; cron mail says 'ptrstat: command not found'; fix ~/oncall/status.sh so it works under cron's PATH.
On-call rule one: reproduce it the way the machine runs it. cron starts scripts with PATH=/usr/bin:/bin, so env -i PATH=/usr/bin:/bin HOME=$HOME bash script.sh shows exactly what cron sees.
Commands taught
oncall-triageLevel 167: The empty variable
Objective: PAGER: someone renamed the key in cache.conf and cleanup.sh ran rm -rf on /; make ~/oncall/cleanup.sh refuse (stderr, exit 1) when CACHE_DIR is empty.
rm -rf "$DIR"/* with an empty DIR becomes rm -rf /*. ${DIR:?message} stops the script with the message when DIR is empty or unset: a guard that costs one line.
Level 168: Backup said OK
Objective: PAGER: restore failed, the archive is truncated, but every nightly log says OK; make ~/oncall/backup.sh fail (stderr, exit 1, no archive left) when tar fails.
In a | b only b's exit status counts, so tar can fail while gzip happily finishes. set -o pipefail makes the pipe fail when any stage fails; then remove the broken archive.
Level 169: Double trouble
Objective: PAGER: total.txt is missing orders whenever counter.sh runs overlap; make ~/oncall/counter.sh wait for a lock (max 10 s) so overlapping runs both count.
Two copies of a read-modify-write job that overlap lose updates: both read 100, both write 105. Take the lock BEFORE reading; flock -w waits its turn, so no run is lost.
Level 170: The alarm that never rang
Objective: PAGER: a brute-force attack went unnoticed; bruteforce.sh always says 'failed logins: 0'; fix ~/oncall/bruteforce.sh so the count and the alarm (exit 1) work.
cmd | while … runs the loop in a subshell: the counter grows in there and vanishes when the loop ends. Feed the loop with done < <(cmd) and it runs in your shell.
Level 171: Permission denied
Objective: PAGER: render.sh fails on the new servers with 'Permission denied' (exit 126); their /tmp is noexec; fix ~/oncall/render.sh (server.env shows their TMPDIR).
Hardened servers mount /tmp noexec: files there can't be executed, even with chmod +x (exit 126). An interpreter can still read them: sh "$tmp" works where "$tmp" doesn't.
Commands taught
noexecLevel 172: Behind the mask
Objective: PAGER: the archive index was half offline, and prune.sh deleted files anyway and said 'pruned'; fix ~/oncall/prune.sh so a failing list-old.sh stops it.
local x=$(cmd) is two things at once, and its exit status is local's (always 0): set -e never sees cmd fail. Declare first, assign on its own line: local x; x=$(cmd).
Level 173: Hangs at 3am
Objective: PAGER: the 03:00 purge job has hung at its prompt for 6 hours; make ~/oncall/purge.sh refuse at once (stderr, exit 1) without a terminal or --yes.
A job runner may hand a script a stdin that never ends: read then waits forever and the job slot stays busy. [ -t 0 ] is true only for a real terminal: no terminal and no --yes means refuse at once.
Level 174: The file named -rf
Objective: PAGER: sweep.sh choked on uploads named '-rf.tmp' and 'my photo.tmp' and deleted a file called 'my'; fix ~/oncall/sweep.sh for any file name.
File names can hold spaces, newlines and a leading dash. $(ls) splits them apart, and a name like -rf.tmp turns into options. Loop over a glob with ./ in front, quote "$f", and end options with --.
Level 175: Disk full
Objective: PAGER: disk 97% full; the logs are never compressed or deleted; fix the find tests in ~/oncall/rotate.sh: gzip .log over 24 h old, delete .gz over 7 days old.
find -mtime N counts whole days and N means exactly N: -mtime 1 is 'between 24 and 48 hours old'. 'Over a day' is -mtime +0, 'over 7 days' is -mtime +6, or say it in minutes with -mmin +1440.
Commands taught
find-ageLevel 176: mapfile: not found
Objective: PAGER: stats.log is full of 'mapfile: not found'; the crontab runs 'sh .../stats.sh'; fix the job so it runs every hour without errors.
sh script.sh ignores the #! line: the script runs in sh (busybox ash, dash on Debian), and bash features like mapfile or arrays fail. Run it with the shell it was written for, or make it POSIX.
Level 177: BOSS: Night of the pager
Objective: PAGER 02:31: nightly.sh 'dump ok' but the dumps are empty, and too few old dumps are kept; find and fix every fault in ~/oncall/nightly.sh.
A real incident has more than one cause. Reproduce it the way cron runs it, then fix one fault at a time and prove each fix.
World 18The Works
10 levelsThree capstones, one tool each: vault-backup, release.sh over two hosts, and fleet-audit. Build, extend, then survive the gauntlet.
Level 178: Capstone 1: first snapshot
Objective: Build ~/works/backup.sh [--dry-run] SRC DEST: a verified, logged tar.gz snapshot of SRC.
A real tool is built in layers: first a correct snapshot, then its checksum, a log line and a rehearsal mode. vault-backup starts here with tar+gzip, sha256sum and --dry-run.
Commands taught
capstone-backupLevel 179: Capstone 1: keep, lock, restore
Objective: Extend backup.sh (seeded with your --keep-days/--restore version): a second copy refuses (flock DEST/.backup.lock, exit 3), writes are atomic.
Two backups running at once corrupt each other, and a half-written archive looks like a real one. A flock lock and an atomic write (temp file, then mv) make the tool safe to run from cron.
Commands taught
capstone-backupflockLevel 180: BOSS: vault-backup gauntlet
Objective: Take over ~/works/backup.sh (inherited, with lint problems): make it lint-clean, harden it, and ship a bats suite for it.
Shipping means someone else can trust it: lint-clean, hostile names handled, failures leave nothing behind, and a test suite that would catch the next bad edit.
Commands taught
capstone-backupptr-lintLevel 181: Capstone 2: staged release
Objective: Build ~/works/release.sh ID: stage ./build into releases/ID, switch current, health-check it over HTTP, and leave nothing behind on failure.
A deploy is a folder you never edit afterwards plus one symlink you flip. Stage the release, rename it into place, switch with ln -sfn, ask the app if it is alive, and clean up after failures.
Commands taught
capstone-releasereleases-symlinkLevel 182: Capstone 2: rollback, prune, lock
Objective: Extend release.sh: unhealthy → back to the previous release (exit 1, 'rolled back'), keep the newest KEEP (default 3) plus the previous one, lock with exit 3.
A deploy tool has to undo itself: an unhealthy release puts the old link back, old releases are pruned but never the way back, and two deploys at once are refused.
Commands taught
capstone-releaserollbackLevel 183: BOSS: release over 2 hosts
Objective: Rebuild release.sh ID for hosts.txt (web1, web2): preflight, ship staged, switch, health-check, roll all back on failure, clean up a failed ship.
The same release, now on two servers: preflight with timeouts, staged copies, one switch, health everywhere, all-or-nothing rollback, and a trap that cleans up a half-finished ship.
Commands taught
capstone-releasessh-remoteLevel 184: Capstone 3: audit one host
Objective: Build ~/works/audit.sh HOST: print {host, disk_pct, uid0, ports} as JSON, and {host, error:"unreachable"} (exit 1) for a host that does not answer.
A fleet audit starts with one host: collect facts over ssh in one call, turn them into data with jq -n, and make a dead host a result instead of a hang.
Commands taught
capstone-auditjqjq-filtersLevel 185: Capstone 3: from JSON to a table
Objective: Build ~/works/report.sh [--table|--worst] FILE...: merge the JSON objects in facts/*.json into one array, a table, or the worst status.
The audit has to speak to humans too (--table for people, --worst for the pager). jq can slurp many objects into one array (-s) and shape rows with if/else, tostring, join and @tsv; a while loop with IFS=$'\t' read then aligns the columns with printf.
Commands taught
jq-filterscapstone-auditLevel 186: Capstone 3: all hosts at once
Objective: Extend audit.sh: with no HOST read hosts.txt, audit all hosts in parallel (& and wait), print one JSON array in file order; --table prints a printf table.
Auditing 20 hosts one by one takes 20 times as long: start every audit in the background with a timeout, wait for all, and assemble one report in a fixed order.
Commands taught
capstone-auditfan-outLevel 187: BOSS: fleet-audit gauntlet
Objective: Extend audit.sh: a status per host (ok/warn/crit), exit 0/1/2 by the worst, --warn/--crit options, and a STATUS column plus a 'worst:' line in --table.
An audit that cannot fail a pipeline is only a report. Give every host a status, return the worst as an exit code (0 ok, 1 warning, 2 critical, like Nagios), and make thresholds options.
Commands taught
capstone-audithealth-checks
World 19The Summit
7 levelsTwo more capstones: logwatch v2, a real monitoring check with time windows and webhooks, and onboard.sh, idempotent account provisioning.
Level 188: Crew checks
Objective: Try each crew check once, exactly as Kern shows it.
Onboarding checks each login and ssh key with a regex before it creates anything. See each one, then type it.
Level 189: Capstone 4: count the errors
Objective: Build ~/summit/logwatch2.sh [--warn N] [--crit N] [--since SPEC] [--json] LOGFILE: count recent ERROR lines and answer like a monitoring plugin.
A monitoring check is a script with a contract: one line of text and an exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN, as Nagios and friends expect). logwatch v2 counts recent ERROR lines against thresholds.
Commands taught
capstone-logwatchdate-mathLevel 190: Capstone 4: tell somebody
Objective: Extend logwatch2.sh with --hook URL: POST the JSON body when not OK; a failing hook only prints 'logwatch2: hook failed' on stderr.
A check that nobody reads is no check: when the status is not OK, POST the JSON to a webhook with a timeout, and never let a broken webhook hide the result or change the exit code.
Commands taught
capstone-logwatchwebhooksLevel 191: BOSS: logwatch v2 windows
Objective: Add repeatable --window 'SPEC:WARN:CRIT' to logwatch2.sh: evaluate every window, report the worst, include them all in --json.
Real alerting looks at several windows at once: a burst in 5 minutes, a drizzle over 3 hours. Each window has its own thresholds; the worst status wins and says which window caused it.
Commands taught
capstone-logwatchdate-mathLevel 192: Capstone 5: new crew
Objective: Build ~/summit/onboard.sh [--dry-run] users.csv (login,name,group,key), run as root: create people idempotently and report created, exists and failed.
Onboarding is a CSV in, accounts out: each person gets a login, a group, a home from /etc/skel and their ssh key with strict permissions. Run twice, nothing changes; run with --dry-run, nothing happens.
Commands taught
capstone-onboardonboardingLevel 193: Capstone 5: the real CSV
Objective: Extend onboard.sh: strip CRLF, refuse UID < 1000 accounts, append a new key to an existing user ('updated LOGIN'), and count updated in the summary.
Real CSVs come from spreadsheets: Windows line endings, repeated people, system accounts like root, and new keys for people who already exist. The tool must cope, stay idempotent and never touch a system account.
Commands taught
capstone-onboardidempotencyLevel 194: BOSS: onboard gauntlet
Objective: Take onboard.sh to production: --dry-run plans updates too, --report FILE writes JSON, and the last CSV line is never skipped.
The final gauntlet: a rehearsal that is a faithful plan, a machine-readable report, and no line lost, not even a CSV that has no newline at its end.
Commands taught
capstone-onboarddry-run
For teachers
Use these levels with a class
SOLUTION HIDDEN Teachers see answer keys in the classroom.