>_ IzzyLab

Hands-on task

This task is step 29 of the course “Bash scripts: from a loop to a robust script”

Publishing doesn't notice the error

medium~7 min

The script /root/publish.sh reads the version from /srv/build/version.txt, packs the site and writes /root/published.txt. The version file is missing right now — and the script still reports success. Enable strict mode set -euo pipefail in it so that on such an error the script stops and /root/published.txt doesn't appear. When the version is in place, publishing must work as before.

What you'll practise:
  • set -euo pipefail
  • pipefail
  • strict mode
  • exit codes
  • fail-fast

Topic breakdown

By default bash doesn't stop on errors, and a pipeline's exit code is the code of its last command. That's why cat missing-file | tr … "succeeds": cat failed, but tr happily processed the empty input. set -e aborts the script on the first failed command, but it doesn't see a failed stage in the middle of a pipeline — for that you need set -o pipefail, after which a pipeline returns the error of any stage. set -u adds one more safeguard: a typo in a variable name becomes an error instead of an empty string. Together this is "strict mode" — the standard preamble of scripts that publish or deploy something.

What's checked

  1. strict mode enabled
  2. without the version file the script stops
  3. with the version file publishing works

What it looks like