Boss lesson · Unit 04
A backup script that fails loudly
set -euo pipefail, quoting disasters, find, tar and cron
What you practise
set -euo pipefailand what each flag stops, unquoted-variable disasters,find ... -execandfind | xargs,taranddatein a filename, running it fromcron
Try a question from this lesson
Pick one
A nightly backup script. One night /data/site is missing, so cd fails. What does the script do next?
cd /data/site
tar -czf /backups/site.tar.gz .
echo "backup done"Correct answer
It carries on and archives whatever folder it is standing in
Why
By default a script shrugs off a failed command and runs the next line. tar archives ., which is now the wrong folder, and overwrites last night's good backup. Then it reports success.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
set -e: stop at the first failure
set -e changes the default: the script exits the moment a command fails.
A failure you handle yourself does not count. That covers the command after if, and the left side of && or ||.
#!/bin/bash
set -e
cd site # fails: script stops
tar -czf site.tar.gz .
echo "backup done"Concept
The safety line
Three switches, written as one line at the top of every script:
-e exit when a command fails.
-u treat an unset variable as an error.
-o pipefail a pipeline fails if any stage fails, not only the last.
Together they turn silent damage into a loud stop at the line that went wrong.
#!/bin/bash
set -euo pipefail10 more exercises in the app
- 3× type the answer
- 4× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.