How to catch errors as soon as they occur in bash scripts
Posted on
Let me introduce you to the power trio you will want to add to your bash scripts in order to fail fast upon error and avoid the script to continue despite the error.
Power trio
By trio I mean the 3 set
builtins to be found in the below code snippet.
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
# Some example commands
npm ci
npm run build
npm run lint
# ...
Here is a run down of what they aim at:
set -o errexit
(short version:set -e
): Exits immediately upon non-zero status.set -o nounset
(short version:set -u
): Exits immediately upon usage of undefined variables.set -o pipefail
: Exits immediately upon failed piped commands.