Skip to content
Lab 1 of 4

Bash That Fails Loudly: The Backup That Said OK

Arjun's nightly receipts backup has printed "backup OK" every night since 2024 — including the nights it backed up nothing. Make it fail loudly with exit codes and set -euo pipefail, refuse to run without its argument, survive a path with a space, and never leave a backup-shaped file behind.
  • Beginner
  • 44 min
  • Bash
  • Scripting
  • Reliability
  • Kestrel

Overview

Neha Arora in finance needs last month's receipts to reconcile against the bank. The backup directory has an archive for every night — and some of them are empty. Arjun's script, /usr/local/bin/backup-receipts, printed backup OK on every one of those nights.

That is the most dangerous kind of script: one that fails quietly. In this lab you fix it the way you should write every script from now on. You will see why a pipeline hides a failure, make the script stop at the first error, give it a usage message and a proper exit status, quote every expansion so a path with a space cannot split it in two, and make sure a failed run can never leave behind a file that looks like a good backup.

The script runs as root via sudo — which is exactly why every one of these mistakes matters.

What you will learn

  • Read exit statuses with $? and know what a script's own status is
  • Use set -euo pipefail and know what each of the three parts catches
  • Validate arguments, print usage on stderr and exit with status 2
  • Quote every expansion so spaces cannot split a path
  • Write to a temporary file, clean up with trap, and publish with an atomic mv

Before you start

  • You can edit a file with nano and run commands with sudo
  • You have seen a bash script before; no scripting experience needed

Tasks

  1. 01Exit codes, and the pipeline that hid a failure
  2. 02No argument, no damage
  3. 03Quote every expansion
  4. 04Never leave a backup-shaped file behind

Next in this course