Skip to the levels
ROOTSPIRE
DiscsFor teachers
▶ Play freeLibrary 16 discsDiscsFor teachersLog in

Every level, in the open

Bash Scripting

19 worlds · 194 levels · 22 bosses

SOLUTION HIDDENTeachers see answer keys in the classroom.

▶ Play this discAll discs
All discsLinux: Zero to RootBash ScriptingGitDatabasesPython for OpsLinux Sysadmin ProNetworkingObservabilityCloud & IaCDocker & ContainersCTF ArenaSOC FieldWindows for Linux peopleKubernetesAnsibleThe Guildhall: First Week

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 1 The ForgeWorld 2 The GateWorld 3 The MillWorld 4 The ArmoryWorld 5 The DockWorld 6 The VaultWorld 7 The PressWorld 8 The TowerWorld 9 Lint HallWorld 10 Style WingWorld 11 Proving GroundWorld 12 The WireWorld 13 The RelayWorld 14 The FleetWorld 15 The HarborWorld 16 Old RoadsWorld 17 On-CallWorld 18 The WorksWorld 19 The Summit

World 1The Forge

11 levels

Where commands become scripts: your first #!, variables, quotes, $( ), math and read.

  1. 1

    Level 1: First spark

    GuidedEasy

    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 taughtshebang

    ▶ Play: First sparkSOLUTION HIDDEN15 XP
  2. 2

    Level 2: Welcome sign

    GuidedEasy

    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 taughtvariables

    ▶ Play: Welcome signSOLUTION HIDDEN15 XP
  3. 3

    Level 3: Name tags

    GuidedEasy

    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 taughtquoting

    ▶ Play: Name tagsSOLUTION HIDDEN20 XP
  4. 4

    Level 4: Hand it down

    GuidedEasy

    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 taughtenvironment

    ▶ Play: Hand it downSOLUTION HIDDEN20 XP
  5. 5

    Level 5: Toolbox

    GuidedEasy

    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 taughtshopt

    ▶ Play: ToolboxSOLUTION HIDDEN15 XP
  6. 6

    Level 6: Headcount

    AloneMedium

    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 taughtcommand-substitution

    ▶ Play: HeadcountSOLUTION HIDDEN25 XP
  7. 7

    Level 7: Quick math

    GuidedEasy

    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.

    ▶ Play: Quick mathSOLUTION HIDDEN15 XP
  8. 8

    Level 8: Damage report

    AloneMedium

    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 taughtarithmetic

    ▶ Play: Damage reportSOLUTION HIDDEN25 XP
  9. 9

    Level 9: Who goes there?

    AloneMedium

    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 taughtread

    ▶ Play: Who goes there?SOLUTION HIDDEN25 XP
  10. 10

    Level 10: Burn after reading

    AloneMedium

    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.

    ▶ Play: Burn after readingSOLUTION HIDDEN25 XP
  11. 11

    Level 11: BOSS: The receipt

    Boss⏱ TimedHard

    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.

    ▶ Play: BOSS: The receiptSOLUTION HIDDEN60 XP

World 2The Gate

10 levels

Where scripts learn to decide: if, tests, [[ ]], case and logic.

  1. 12

    Level 12: The key

    GuidedEasy

    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 taughtif-test

    ▶ Play: The keySOLUTION HIDDEN15 XP
  2. 13

    Level 13: Test bench

    GuidedEasy

    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.

    ▶ Play: Test benchSOLUTION HIDDEN15 XP
  3. 14

    Level 14: Veterans only

    GuidedEasy

    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 taughtnumeric-tests

    ▶ Play: Veterans onlySOLUTION HIDDEN20 XP
  4. 15

    Level 15: Badge check

    GuidedEasy

    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 taughtdouble-brackets

    ▶ Play: Badge checkSOLUTION HIDDEN20 XP
  5. 16

    Level 16: Dictionary order

    GuidedEasy

    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.

    ▶ Play: Dictionary orderSOLUTION HIDDEN20 XP
  6. 17

    Level 17: The lever

    AloneMedium

    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 taughtcase

    ▶ Play: The leverSOLUTION HIDDEN25 XP
  7. 18

    Level 18: Supply drop

    AloneMedium

    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 taughtlogical-operators

    ▶ Play: Supply dropSOLUTION HIDDEN25 XP
  8. 19

    Level 19: Take it apart

    AloneMedium

    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 ]].

    ▶ Play: Take it apartSOLUTION HIDDEN25 XP
  9. 20

    Level 20: Triage

    Alone⏱ TimedHard

    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.

    ▶ Play: TriageSOLUTION HIDDEN40 XP
  10. 21

    Level 21: BOSS: The gatekeeper

    Boss⏱ TimedHard

    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.

    ▶ Play: BOSS: The gatekeeperSOLUTION HIDDEN60 XP

World 3The Mill

12 levels

Where one job happens a thousand times: for, globs, ${f%.ext}, while read, break and continue.

  1. 22

    Level 22: Countdown

    GuidedEasy

    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 taughtfor-loops

    ▶ Play: CountdownSOLUTION HIDDEN15 XP
  2. 23

    Level 23: Wait for it

    GuidedEasy

    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 taughtuntil-loops

    ▶ Play: Wait for itSOLUTION HIDDEN20 XP
  3. 24

    Level 24: Roll call

    GuidedEasy

    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 taughtglobbing

    ▶ Play: Roll callSOLUTION HIDDEN20 XP
  4. 25

    Level 25: Empty-handed

    GuidedEasy

    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.

    ▶ Play: Empty-handedSOLUTION HIDDEN20 XP
  5. 26

    Level 26: Strip the tags

    GuidedEasy

    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 taughtparam-expansion

    ▶ Play: Strip the tagsSOLUTION HIDDEN20 XP
  6. 27

    Level 27: Loop yard

    GuidedEasy

    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 taughtseq

    ▶ Play: Loop yardSOLUTION HIDDEN15 XP
  7. 28

    Level 28: Tally

    AloneMedium

    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 taughtwhile-readseq

    ▶ Play: TallySOLUTION HIDDEN25 XP
  8. 29

    Level 29: The sieve

    AloneMedium

    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 taughtbreak-continue

    ▶ Play: The sieveSOLUTION HIDDEN25 XP
  9. 30

    Level 30: Dash names

    AloneMedium

    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'.

    ▶ Play: Dash namesSOLUTION HIDDEN25 XP
  10. 31

    Level 31: The vanishing count

    AloneMedium

    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.

    ▶ Play: The vanishing countSOLUTION HIDDEN25 XP
  11. 32

    Level 32: Photo flood

    Alone⏱ TimedHard

    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.

    ▶ Play: Photo floodSOLUTION HIDDEN40 XP
  12. 33

    Level 33: BOSS: The mill report

    Boss⏱ TimedHard

    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*").

    ▶ Play: BOSS: The mill reportSOLUTION HIDDEN65 XP

World 4The Armory

12 levels

Where scripts become tools: functions, return codes, local, arrays and maps.

  1. 34

    Level 34: The hammer

    GuidedEasy

    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 taughtfunctions

    ▶ Play: The hammerSOLUTION HIDDEN15 XP
  2. 35

    Level 35: Even or odd

    GuidedEasy

    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 taughtreturn

    ▶ Play: Even or oddSOLUTION HIDDEN20 XP
  3. 36

    Level 36: The side room

    GuidedEasy

    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 taughtsubshell

    ▶ Play: The side roomSOLUTION HIDDEN20 XP
  4. 37

    Level 37: Weapon rack

    GuidedEasy

    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 taughtarrays

    ▶ Play: Weapon rackSOLUTION HIDDEN20 XP
  5. 38

    Level 38: Tool belt

    GuidedEasy

    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.

    ▶ Play: Tool beltSOLUTION HIDDEN15 XP
  6. 39

    Level 39: No leaks

    AloneMedium

    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 taughtlocal

    ▶ Play: No leaksSOLUTION HIDDEN25 XP
  7. 40

    Level 40: Locked box

    GuidedEasy

    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 taughtreadonly

    ▶ Play: Locked boxSOLUTION HIDDEN20 XP
  8. 41

    Level 41: Reverse march

    AloneMedium

    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.

    ▶ Play: Reverse marchSOLUTION HIDDEN25 XP
  9. 42

    Level 42: Build the command

    AloneMedium

    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.

    ▶ Play: Build the commandSOLUTION HIDDEN25 XP
  10. 43

    Level 43: Loot count

    AloneMedium

    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 taughtassoc-arrays

    ▶ Play: Loot countSOLUTION HIDDEN30 XP
  11. 44

    Level 44: Is it there?

    GuidedEasy

    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.

    ▶ Play: Is it there?SOLUTION HIDDEN20 XP
  12. 45

    Level 45: BOSS: The quartermaster

    Boss⏱ TimedHard

    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.

    ▶ Play: BOSS: The quartermasterSOLUTION HIDDEN65 XP

World 5The Dock

9 levels

Where scripts take orders: $1, "$@", shift, usage errors and getopts.

  1. 46

    Level 46: Signal drill

    GuidedEasy

    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.

    ▶ Play: Signal drillSOLUTION HIDDEN15 XP
  2. 47

    Level 47: Hail the ship

    GuidedEasy

    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 taughtpositional-args

    ▶ Play: Hail the shipSOLUTION HIDDEN15 XP
  3. 48

    Level 48: The manifest

    GuidedEasy

    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 taughtall-args

    ▶ Play: The manifestSOLUTION HIDDEN20 XP
  4. 49

    Level 49: Knots

    GuidedEasy

    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 taughtshift

    ▶ Play: KnotsSOLUTION HIDDEN20 XP
  5. 50

    Level 50: The signal flag

    GuidedEasy

    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 taughtgetopts

    ▶ Play: The signal flagSOLUTION HIDDEN22 XP
  6. 51

    Level 51: Two ropes

    AloneMedium

    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 taughtusage

    ▶ Play: Two ropesSOLUTION HIDDEN25 XP
  7. 52

    Level 52: The horn

    AloneMedium

    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.

    ▶ Play: The hornSOLUTION HIDDEN30 XP
  8. 53

    Level 53: Cargo weight

    Alone⏱ TimedHard

    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.

    ▶ Play: Cargo weightSOLUTION HIDDEN40 XP
  9. 54

    Level 54: BOSS: The packer

    Boss⏱ TimedHard

    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.

    ▶ Play: BOSS: The packerSOLUTION HIDDEN65 XP

World 6The Vault

13 levels

Where failures are caught: exit codes, guards, set -euo pipefail, traps and signals.

  1. 55

    Level 55: The probe

    GuidedEasy

    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 taughtexit-codes

    ▶ Play: The probeSOLUTION HIDDEN15 XP
  2. 56

    Level 56: Port check

    GuidedEasy

    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 taughtguards

    ▶ Play: Port checkSOLUTION HIDDEN20 XP
  3. 57

    Level 57: Safety net

    GuidedEasy

    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 taughtsleep

    ▶ Play: Safety netSOLUTION HIDDEN15 XP
  4. 58

    Level 58: Strict mode

    GuidedEasy

    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 taughtstrict-mode

    ▶ Play: Strict modeSOLUTION HIDDEN20 XP
  5. 59

    Level 59: Trapdoor

    GuidedEasy

    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 taughttrap

    ▶ Play: TrapdoorSOLUTION HIDDEN20 XP
  6. 60

    Level 60: Leaky pipe

    AloneMedium

    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 taughtpipefail

    ▶ Play: Leaky pipeSOLUTION HIDDEN25 XP
  7. 61

    Level 61: Every stage

    GuidedEasy

    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.

    ▶ Play: Every stageSOLUTION HIDDEN20 XP
  8. 62

    Level 62: One log

    GuidedEasy

    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 taughtexec-redirect

    ▶ Play: One logSOLUTION HIDDEN20 XP
  9. 63

    Level 63: The mask

    AloneMedium

    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).

    ▶ Play: The maskSOLUTION HIDDEN25 XP
  10. 64

    Level 64: Careful purge

    AloneMedium

    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.

    ▶ Play: Careful purgeSOLUTION HIDDEN25 XP
  11. 65

    Level 65: Night watch

    AloneMedium

    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 taughtsleep

    ▶ Play: Night watchSOLUTION HIDDEN30 XP
  12. 66

    Level 66: Backup guard

    Alone⏱ TimedHard

    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 $?.

    ▶ Play: Backup guardSOLUTION HIDDEN40 XP
  13. 67

    Level 67: BOSS: Release night

    Boss⏱ TimedHard

    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.

    ▶ Play: BOSS: Release nightSOLUTION HIDDEN70 XP

World 7The Press

8 levels

Where text gets processed: IFS, printf, here-docs, awk, sed -i and pipelines in scripts.

  1. 68

    Level 68: Word edges

    GuidedEasy

    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.

    ▶ Play: Word edgesSOLUTION HIDDEN15 XP
  2. 69

    Level 69: The roster

    GuidedEasy

    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 taughtifs

    ▶ Play: The rosterSOLUTION HIDDEN15 XP
  3. 70

    Level 70: The ledger

    GuidedEasy

    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 taughtprintf

    ▶ Play: The ledgerSOLUTION HIDDEN20 XP
  4. 71

    Level 71: The scroll

    GuidedEasy

    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 taughtheredoc

    ▶ Play: The scrollSOLUTION HIDDEN20 XP
  5. 72

    Level 72: Gold tally

    AloneMedium

    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 taughtawk

    ▶ Play: Gold tallySOLUTION HIDDEN25 XP
  6. 73

    Level 73: Spellcheck

    AloneMedium

    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 taughtsed-inplace

    ▶ Play: SpellcheckSOLUTION HIDDEN30 XP
  7. 74

    Level 74: Broken links

    Alone⏱ TimedHard

    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.

    ▶ Play: Broken linksSOLUTION HIDDEN45 XP
  8. 75

    Level 75: BOSS: The morning edition

    Boss⏱ TimedHard

    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.

    ▶ Play: BOSS: The morning editionSOLUTION HIDDEN70 XP

World 8The Tower

10 levels

Where scripts run on their own: bash -x, classic pitfalls, cron, logging, locks, and the final tool.

  1. 76

    Level 76: The trace

    GuidedEasy

    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 taughtdebugging

    ▶ Play: The traceSOLUTION HIDDEN15 XP
  2. 77

    Level 77: Line by line

    GuidedEasy

    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.

    ▶ Play: Line by lineSOLUTION HIDDEN20 XP
  3. 78

    Level 78: Space invaders

    GuidedEasy

    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 taughtpitfalls

    ▶ Play: Space invadersSOLUTION HIDDEN20 XP
  4. 79

    Level 79: Night shift

    GuidedEasy

    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 taughtcron

    ▶ Play: Night shiftSOLUTION HIDDEN20 XP
  5. 80

    Level 80: Tower tools

    GuidedEasy

    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 taughtflock

    ▶ Play: Tower toolsSOLUTION HIDDEN15 XP
  6. 81

    Level 81: The logbook

    AloneMedium

    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 taughtlogging

    ▶ Play: The logbookSOLUTION HIDDEN25 XP
  7. 82

    Level 82: One at a time

    AloneMedium

    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 taughtflock

    ▶ Play: One at a timeSOLUTION HIDDEN30 XP
  8. 83

    Level 83: The haunted script

    Alone⏱ TimedHard

    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.

    ▶ Play: The haunted scriptSOLUTION HIDDEN45 XP
  9. 84

    Level 84: Heartbeat

    Alone⏱ TimedHard

    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.

    ▶ Play: HeartbeatSOLUTION HIDDEN45 XP
  10. 85

    Level 85: FINAL BOSS: logwatch

    Boss⏱ TimedHard

    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 taughtlogwatch

    ▶ Play: FINAL BOSS: logwatchSOLUTION HIDDEN100 XP

World 9Lint Hall

8 levels

Where scripts get read before they run: ptr-lint findings, ShellCheck codes, and the fixes that keep servers alive.

  1. 86

    Level 86: Old ways

    GuidedEasy

    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 taughtdirname-basename

    ▶ Play: Old waysSOLUTION HIDDEN15 XP
  2. 87

    Level 87: First finding

    GuidedEasy

    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 taughtptr-lintshellcheck-codes

    ▶ Play: First findingSOLUTION HIDDEN20 XP
  3. 88

    Level 88: Masked failure

    GuidedEasy

    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).

    ▶ Play: Masked failureSOLUTION HIDDEN20 XP
  4. 89

    Level 89: When it fires

    GuidedEasy

    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.

    ▶ Play: When it firesSOLUTION HIDDEN20 XP
  5. 90

    Level 90: Safe landing

    GuidedEasy

    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:?}"/*).

    ▶ Play: Safe landingSOLUTION HIDDEN25 XP
  6. 91

    Level 91: Words aren't lines

    AloneMedium

    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.

    ▶ Play: Words aren't linesSOLUTION HIDDEN30 XP
  7. 92

    Level 92: Old scrolls

    AloneMedium

    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 taughtlegacy-syntax

    ▶ Play: Old scrollsSOLUTION HIDDEN30 XP
  8. 93

    Level 93: BOSS: Zero findings

    Boss⏱ TimedHard

    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.

    ▶ Play: BOSS: Zero findingsSOLUTION HIDDEN90 XP

World 10Style Wing

8 levels

Scripts other people can read: headers, main, constants, shfmt, reviewing generated code, and knowing when to stop.

  1. 94

    Level 94: Name plate

    GuidedEasy

    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 taughtscript-header

    ▶ Play: Name plateSOLUTION HIDDEN20 XP
  2. 95

    Level 95: String tricks

    GuidedEasy

    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.

    ▶ Play: String tricksSOLUTION HIDDEN15 XP
  3. 96

    Level 96: Main gate

    AloneMedium

    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 taughtmain-function

    ▶ Play: Main gateSOLUTION HIDDEN30 XP
  4. 97

    Level 97: One name, one number

    AloneMedium

    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 taughtnaming

    ▶ Play: One name, one numberSOLUTION HIDDEN30 XP
  5. 98

    Level 98: Straight lines

    GuidedEasy

    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 taughtshfmt

    ▶ Play: Straight linesSOLUTION HIDDEN20 XP
  6. 99

    Level 99: The AI wrote this

    Alone⏱ TimedHard

    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 taughtcode-review

    ▶ Play: The AI wrote thisSOLUTION HIDDEN45 XP
  7. 100

    Level 100: The right tool

    Alone⏱ TimedHard

    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 taughtwhen-not-bash

    ▶ Play: The right toolSOLUTION HIDDEN35 XP
  8. 101

    Level 101: BOSS: Clean room

    Boss⏱ TimedHard

    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.

    ▶ Play: BOSS: Clean roomSOLUTION HIDDEN100 XP

World 11Proving Ground

13 levels

Where scripts earn trust: golden files, assert helpers, bats tests, test doubles, CI, and a hunt for mutants.

  1. 102

    Level 102: Assert tour

    GuidedEasy

    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.

    ▶ Play: Assert tourSOLUTION HIDDEN15 XP
  2. 103

    Level 103: Golden output

    GuidedEasy

    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 taughtdiff

    ▶ Play: Golden outputSOLUTION HIDDEN20 XP
  3. 104

    Level 104: Say it plainly

    GuidedEasy

    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 taughtassert-helpers

    ▶ Play: Say it plainlySOLUTION HIDDEN20 XP
  4. 105

    Level 105: First @test

    GuidedEasy

    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 taughtbats

    ▶ Play: First @testSOLUTION HIDDEN20 XP
  5. 106

    Level 106: Fail loudly

    GuidedEasy

    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 taughterr-trap

    ▶ Play: Fail loudlySOLUTION HIDDEN20 XP
  6. 107

    Level 107: Run, then judge

    AloneMedium

    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 taughtbats-run

    ▶ Play: Run, then judgeSOLUTION HIDDEN30 XP
  7. 108

    Level 108: Clean bench

    AloneMedium

    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 taughttest-fixtures

    ▶ Play: Clean benchSOLUTION HIDDEN30 XP
  8. 109

    Level 109: Two streams

    AloneMedium

    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 taughttest-streams

    ▶ Play: Two streamsSOLUTION HIDDEN30 XP
  9. 110

    Level 110: Stand-ins

    Alone⏱ TimedHard

    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 taughttest-doubles

    ▶ Play: Stand-insSOLUTION HIDDEN40 XP
  10. 111

    Level 111: Edge cases

    Alone⏱ TimedHard

    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 taughtedge-cases

    ▶ Play: Edge casesSOLUTION HIDDEN40 XP
  11. 112

    Level 112: The one that got away

    Alone⏱ TimedHard

    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 taughtregression-tests

    ▶ Play: The one that got awaySOLUTION HIDDEN40 XP
  12. 113

    Level 113: One button

    Alone⏱ TimedHard

    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 taughtci-script

    ▶ Play: One buttonSOLUTION HIDDEN40 XP
  13. 114

    Level 114: BOSS: Mutant hunt

    Boss⏱ TimedHard

    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.

    ▶ Play: BOSS: Mutant huntSOLUTION HIDDEN120 XP

World 12The Wire

10 levels

Where scripts talk to servers: jq for JSON, curl for HTTP, honest status codes, retries with backoff and paged APIs.

  1. 115

    Level 115: jq ladder

    GuidedEasy

    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.

    ▶ Play: jq ladderSOLUTION HIDDEN15 XP
  2. 116

    Level 116: The label

    GuidedEasy

    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 taughtjq

    ▶ Play: The labelSOLUTION HIDDEN15 XP
  3. 117

    Level 117: Strings attached

    GuidedEasy

    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.

    ▶ Play: Strings attachedSOLUTION HIDDEN20 XP
  4. 118

    Level 118: The filter

    AloneMedium

    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.

    ▶ Play: The filterSOLUTION HIDDEN25 XP
  5. 119

    Level 119: Safe envelope

    AloneMedium

    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.

    ▶ Play: Safe envelopeSOLUTION HIDDEN25 XP
  6. 120

    Level 120: First call

    GuidedEasy

    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 taughtcurl

    ▶ Play: First callSOLUTION HIDDEN20 XP
  7. 121

    Level 121: curl ladder

    GuidedEasy

    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.

    ▶ Play: curl ladderSOLUTION HIDDEN15 XP
  8. 122

    Level 122: Status line

    AloneMedium

    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.

    ▶ Play: Status lineSOLUTION HIDDEN30 XP
  9. 123

    Level 123: Try, try again

    AloneMedium

    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 taughtretries

    ▶ Play: Try, try againSOLUTION HIDDEN35 XP
  10. 124

    Level 124: BOSS: The long list

    Boss⏱ TimedHard

    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 taughtpagination

    ▶ Play: BOSS: The long listSOLUTION HIDDEN100 XP

World 13The Relay

10 levels

Where data is passed along: NUL-safe xargs, parallel runs, date math, real CSV, health checks, webhooks and a sync plan.

  1. 125

    Level 125: Null and safe

    GuidedEasy

    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 taughtxargs

    ▶ Play: Null and safeSOLUTION HIDDEN20 XP
  2. 126

    Level 126: How old?

    GuidedEasy

    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 taughtdate-math

    ▶ Play: How old?SOLUTION HIDDEN20 XP
  3. 127

    Level 127: awk ladder

    GuidedEasy

    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.

    ▶ Play: awk ladderSOLUTION HIDDEN15 XP
  4. 128

    Level 128: Field day

    AloneMedium

    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 taughtawk-fields

    ▶ Play: Field daySOLUTION HIDDEN25 XP
  5. 129

    Level 129: Relay tools

    GuidedEasy

    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.

    ▶ Play: Relay toolsSOLUTION HIDDEN15 XP
  6. 130

    Level 130: Pulse

    AloneMedium

    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 taughthealth-checks

    ▶ Play: PulseSOLUTION HIDDEN35 XP
  7. 131

    Level 131: Ring the bell

    AloneMedium

    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 taughtwebhooks

    ▶ Play: Ring the bellSOLUTION HIDDEN30 XP
  8. 132

    Level 132: Many hands

    Alone⏱ TimedHard

    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.

    ▶ Play: Many handsSOLUTION HIDDEN40 XP
  9. 133

    Level 133: Stale jobs

    Alone⏱ TimedHard

    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.

    ▶ Play: Stale jobsSOLUTION HIDDEN45 XP
  10. 134

    Level 134: BOSS: api-sync

    Boss⏱ TimedHard

    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 taughtapi-sync

    ▶ Play: BOSS: api-syncSOLUTION HIDDEN120 XP

World 14The Fleet

9 levels

Many machines, one script: ssh in loops, remote scripts, idempotent edits, install, dry runs, fan-out.

  1. 135

    Level 135: Roll call

    GuidedEasy

    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 taughtssh-remote

    ▶ Play: Roll callSOLUTION HIDDEN15 XP
  2. 136

    Level 136: Fleet tools

    GuidedEasy

    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.

    ▶ Play: Fleet toolsSOLUTION HIDDEN15 XP
  3. 137

    Level 137: The hosts file

    AloneMedium

    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.

    ▶ Play: The hosts fileSOLUTION HIDDEN25 XP
  4. 138

    Level 138: Carry the script

    AloneMedium

    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.

    ▶ Play: Carry the scriptSOLUTION HIDDEN25 XP
  5. 139

    Level 139: Say it once

    GuidedEasy

    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 taughtidempotency

    ▶ Play: Say it onceSOLUTION HIDDEN20 XP
  6. 140

    Level 140: Set, don't stack

    AloneMedium

    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.

    ▶ Play: Set, don't stackSOLUTION HIDDEN30 XP
  7. 141

    Level 141: One move

    AloneMedium

    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 taughtinstall

    ▶ Play: One moveSOLUTION HIDDEN25 XP
  8. 142

    Level 142: Rehearsal

    GuidedEasy

    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 taughtdry-run

    ▶ Play: RehearsalSOLUTION HIDDEN20 XP
  9. 143

    Level 143: BOSS: Fan-out

    Boss⏱ TimedHard

    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 taughtfan-out

    ▶ Play: BOSS: Fan-outSOLUTION HIDDEN100 XP

World 15The Harbor

10 levels

Where releases ship: confirmations, secrets, .env files, symlink switches, health checks, rollbacks, onboarding.

  1. 144

    Level 144: Harbor keys

    GuidedEasy

    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 taughtreadlink

    ▶ Play: Harbor keysSOLUTION HIDDEN15 XP
  2. 145

    Level 145: Are you sure?

    GuidedEasy

    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 taughtconfirm-prompts

    ▶ Play: Are you sure?SOLUTION HIDDEN20 XP
  3. 146

    Level 146: Loose lips

    AloneMedium

    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 taughtsecrets

    ▶ Play: Loose lipsSOLUTION HIDDEN30 XP
  4. 147

    Level 147: Data, not code

    AloneMedium

    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 taughtenv-files

    ▶ Play: Data, not codeSOLUTION HIDDEN30 XP
  5. 148

    Level 148: The switch

    GuidedEasy

    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 taughtreleases-symlink

    ▶ Play: The switchSOLUTION HIDDEN20 XP
  6. 149

    Level 149: Is it alive?

    AloneMedium

    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 taughtdeploy-health

    ▶ Play: Is it alive?SOLUTION HIDDEN30 XP
  7. 150

    Level 150: The way back

    Alone⏱ TimedHard

    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 taughtrollbackreadlink

    ▶ Play: The way backSOLUTION HIDDEN45 XP
  8. 151

    Level 151: New hands

    GuidedEasy

    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 taughtbase64onboarding

    ▶ Play: New handsSOLUTION HIDDEN15 XP
  9. 152

    Level 152: New crew

    Alone⏱ TimedHard

    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 taughtonboarding

    ▶ Play: New crewSOLUTION HIDDEN50 XP
  10. 153

    Level 153: BOSS: Deploy day

    Boss⏱ TimedHard

    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.

    ▶ Play: BOSS: Deploy daySOLUTION HIDDEN120 XP

World 16Old Roads

10 levels

Where shells start and scripts travel: startup files, PATH, aliases, bashisms, CRLF, old idioms, printf, and one script that runs the same everywhere.

  1. 154

    Level 154: Who reads what?

    GuidedEasy

    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 taughtlogin-shellsprofile-files

    ▶ Play: Who reads what?SOLUTION HIDDEN20 XP
  2. 155

    Level 155: A road for ~/bin

    GuidedEasy

    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 taughtpath-varlogin-shells

    ▶ Play: A road for ~/binSOLUTION HIDDEN20 XP
  3. 156

    Level 156: Aliases stay home

    GuidedEasy

    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 taughtaliasfunctions

    ▶ Play: Aliases stay homeSOLUTION HIDDEN20 XP
  4. 157

    Level 157: Spot the bashism

    GuidedEasy

    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 taughtposix-shbashisms

    ▶ Play: Spot the bashismSOLUTION HIDDEN20 XP
  5. 158

    Level 158: Port it to sh

    AloneMedium

    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 taughtposix-shbashismssort-fields

    ▶ Play: Port it to shSOLUTION HIDDEN30 XP
  6. 159

    Level 159: Ask for bash by name

    AloneMedium

    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 taughtenv-shebang

    ▶ Play: Ask for bash by nameSOLUTION HIDDEN30 XP
  7. 160

    Level 160: The invisible ^M

    AloneMedium

    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 taughtcrlfsed-inplace

    ▶ Play: The invisible ^MSOLUTION HIDDEN30 XP
  8. 161

    Level 161: Read the old scrolls

    AloneMedium

    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 taughtold-idiomslegacy-syntax

    ▶ Play: Read the old scrollsSOLUTION HIDDEN30 XP
  9. 162

    Level 162: echo is not portable

    Alone⏱ TimedHard

    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 taughtprintfposix-sh

    ▶ Play: echo is not portableSOLUTION HIDDEN45 XP
  10. 163

    Level 163: BOSS: Same everywhere

    Boss⏱ TimedHard

    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 taughtsort-fields

    ▶ Play: BOSS: Same everywhereSOLUTION HIDDEN120 XP

World 17On-Call

14 levels

The pager rings for scripts that broke in production: reproduce like cron, find the cause, fix it, prove it.

  1. 164

    Level 164: Dump peek

    GuidedEasy

    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.

    ▶ Play: Dump peekSOLUTION HIDDEN15 XP
  2. 165

    Level 165: The on-call kit

    GuidedEasy

    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 taughtdbdump

    ▶ Play: The on-call kitSOLUTION HIDDEN20 XP
  3. 166

    Level 166: Works on my machine

    GuidedEasy

    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 taughtoncall-triage

    ▶ Play: Works on my machineSOLUTION HIDDEN30 XP
  4. 167

    Level 167: The empty variable

    GuidedEasy

    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.

    ▶ Play: The empty variableSOLUTION HIDDEN30 XP
  5. 168

    Level 168: Backup said OK

    AloneMedium

    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.

    ▶ Play: Backup said OKSOLUTION HIDDEN40 XP
  6. 169

    Level 169: Double trouble

    Alone⏱ TimedMedium

    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.

    ▶ Play: Double troubleSOLUTION HIDDEN40 XP
  7. 170

    Level 170: The alarm that never rang

    AloneMedium

    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.

    ▶ Play: The alarm that never rangSOLUTION HIDDEN40 XP
  8. 171

    Level 171: Permission denied

    AloneMedium

    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 taughtnoexec

    ▶ Play: Permission deniedSOLUTION HIDDEN40 XP
  9. 172

    Level 172: Behind the mask

    Alone⏱ TimedHard

    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).

    ▶ Play: Behind the maskSOLUTION HIDDEN50 XP
  10. 173

    Level 173: Hangs at 3am

    Alone⏱ TimedHard

    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.

    ▶ Play: Hangs at 3amSOLUTION HIDDEN50 XP
  11. 174

    Level 174: The file named -rf

    Alone⏱ TimedHard

    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 --.

    ▶ Play: The file named -rfSOLUTION HIDDEN50 XP
  12. 175

    Level 175: Disk full

    Alone⏱ TimedHard

    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 taughtfind-age

    ▶ Play: Disk fullSOLUTION HIDDEN50 XP
  13. 176

    Level 176: mapfile: not found

    Alone⏱ TimedHard

    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.

    ▶ Play: mapfile: not foundSOLUTION HIDDEN50 XP
  14. 177

    Level 177: BOSS: Night of the pager

    Boss⏱ TimedHard

    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.

    ▶ Play: BOSS: Night of the pagerSOLUTION HIDDEN150 XP

World 18The Works

10 levels

Three capstones, one tool each: vault-backup, release.sh over two hosts, and fleet-audit. Build, extend, then survive the gauntlet.

  1. 178

    Level 178: Capstone 1: first snapshot

    GuidedEasy

    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 taughtcapstone-backup

    ▶ Play: Capstone 1: first snapshotSOLUTION HIDDEN60 XP
  2. 179

    Level 179: Capstone 1: keep, lock, restore

    Alone⏱ TimedHard

    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 taughtcapstone-backupflock

    ▶ Play: Capstone 1: keep, lock, restoreSOLUTION HIDDEN70 XP
  3. 180

    Level 180: BOSS: vault-backup gauntlet

    Boss⏱ TimedHard

    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 taughtcapstone-backupptr-lint

    ▶ Play: BOSS: vault-backup gauntletSOLUTION HIDDEN150 XP
  4. 181

    Level 181: Capstone 2: staged release

    GuidedEasy

    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 taughtcapstone-releasereleases-symlink

    ▶ Play: Capstone 2: staged releaseSOLUTION HIDDEN60 XP
  5. 182

    Level 182: Capstone 2: rollback, prune, lock

    Alone⏱ TimedHard

    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 taughtcapstone-releaserollback

    ▶ Play: Capstone 2: rollback, prune, lockSOLUTION HIDDEN70 XP
  6. 183

    Level 183: BOSS: release over 2 hosts

    Boss⏱ TimedHard

    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 taughtcapstone-releasessh-remote

    ▶ Play: BOSS: release over 2 hostsSOLUTION HIDDEN150 XP
  7. 184

    Level 184: Capstone 3: audit one host

    GuidedEasy

    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 taughtcapstone-auditjqjq-filters

    ▶ Play: Capstone 3: audit one hostSOLUTION HIDDEN60 XP
  8. 185

    Level 185: Capstone 3: from JSON to a table

    GuidedEasy

    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 taughtjq-filterscapstone-audit

    ▶ Play: Capstone 3: from JSON to a tableSOLUTION HIDDEN50 XP
  9. 186

    Level 186: Capstone 3: all hosts at once

    Alone⏱ TimedHard

    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 taughtcapstone-auditfan-out

    ▶ Play: Capstone 3: all hosts at onceSOLUTION HIDDEN70 XP
  10. 187

    Level 187: BOSS: fleet-audit gauntlet

    Boss⏱ TimedHard

    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 taughtcapstone-audithealth-checks

    ▶ Play: BOSS: fleet-audit gauntletSOLUTION HIDDEN150 XP

World 19The Summit

7 levels

Two more capstones: logwatch v2, a real monitoring check with time windows and webhooks, and onboard.sh, idempotent account provisioning.

  1. 188

    Level 188: Crew checks

    GuidedEasy

    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.

    ▶ Play: Crew checksSOLUTION HIDDEN15 XP
  2. 189

    Level 189: Capstone 4: count the errors

    GuidedEasy

    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 taughtcapstone-logwatchdate-math

    ▶ Play: Capstone 4: count the errorsSOLUTION HIDDEN60 XP
  3. 190

    Level 190: Capstone 4: tell somebody

    Alone⏱ TimedHard

    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 taughtcapstone-logwatchwebhooks

    ▶ Play: Capstone 4: tell somebodySOLUTION HIDDEN70 XP
  4. 191

    Level 191: BOSS: logwatch v2 windows

    Boss⏱ TimedHard

    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 taughtcapstone-logwatchdate-math

    ▶ Play: BOSS: logwatch v2 windowsSOLUTION HIDDEN150 XP
  5. 192

    Level 192: Capstone 5: new crew

    GuidedEasy

    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 taughtcapstone-onboardonboarding

    ▶ Play: Capstone 5: new crewSOLUTION HIDDEN60 XP
  6. 193

    Level 193: Capstone 5: the real CSV

    Alone⏱ TimedHard

    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 taughtcapstone-onboardidempotency

    ▶ Play: Capstone 5: the real CSVSOLUTION HIDDEN70 XP
  7. 194

    Level 194: BOSS: onboard gauntlet

    Boss⏱ TimedHard

    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 taughtcapstone-onboarddry-run

    ▶ Play: BOSS: onboard gauntletSOLUTION HIDDEN160 XP

For teachers

Use these levels with a class

SOLUTION HIDDEN Teachers see answer keys in the classroom.

For teachers
ROOTSPIRE
DiscsFor teachers
▶ Play freeLibrary 16 discsDiscsFor teachersLog in