Bash That Fails Loudly: The Backup That Said OK
- 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 pipefailand 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 atomicmv
Before you start
- You can edit a file with
nanoand run commands withsudo - You have seen a bash script before; no scripting experience needed
Tasks
- 01Exit codes, and the pipeline that hid a failure
- 02No argument, no damage
- 03Quote every expansion
- 04Never leave a backup-shaped file behind