Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readDev Tool

Make bash scripts fail fast

Use set -euo pipefail to catch common Bash failures and learn where errexit has exceptions.

Your deploy script copied a file that did not exist, printed an error, and then carried on to the next line. By default, a failed simple command can leave Bash running the rest of the script.

The set builtin has three options that change that. Run them one at a time to see the effect. The error wording varies with your system.

$ bash -c 'cp missing.txt backup.txt; echo "deploying"'
cp: cannot stat 'missing.txt': No such file or directory
deploying
$ bash -e -c 'cp missing.txt backup.txt; echo "deploying"'
cp: cannot stat 'missing.txt': No such file or directory
$ bash -c 'false | cat; echo "pipeline status: $?"'
pipeline status: 0
$ bash -o pipefail -c 'false | cat; echo "pipeline status: $?"'
pipeline status: 1
$ bash -c 'echo "removing /tmp/${BUILD_DIR}/cache"'
removing /tmp//cache
$ bash -u -c 'echo "removing /tmp/${BUILD_DIR}/cache"'
bash: line 1: BUILD_DIR: unbound variable

Without flags, the failed cp is followed by deploying and the failed false in a pipeline reports 0. The unset variable expands to nothing, so the path becomes /tmp//cache.

What each flag changes

  • -e exits the script for unhandled failures in contexts where errexit applies. The second cp stops the run, and deploying never prints.
  • -o pipefail makes a pipeline return the status of the rightmost command that failed, or zero when all commands succeed. false | cat reports 1.
  • -u treats an unset variable as an error. The typo in BUILD_DIR now stops the script instead of building a path to the wrong directory.

Enable all three near the top of a Bash script.

#!/usr/bin/env bash
set -euo pipefail

Where -e looks away

Bash ignores -e for a command that sits in a condition. That means an if or while test, or any command in an && or || list except the last. The exemption also applies inside a function you call in one of those positions. Bash exempts commands with an inverted status (!) and handles earlier pipeline failures through pipefail.

#!/usr/bin/env bash
set -euo pipefail

check() { false; echo "check kept going"; }
check || echo "handled"
echo "script kept going"

The output is check kept going and script kept going. The false did not stop the function, and handled never printed. Remove the || echo "handled" and the same function stops at false, so the script exits with status 1.

Call the function on its own line for fail-fast behaviour. If you need to handle failure at the call site, have the function return a failure explicitly, for example with copy_files || return.