Konubinix' opinionated web of thoughts

Defensive Programming With Bash

fleeting

Defensive programming with bash

According to https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/, use src_sh[:exports code]{set -Eeuo pipefail}

set -e
The -e option will cause a bash script to exit immediately when a command fails.
set -o pipefail
Sets the exit code of a pipeline to that of the rightmost command to exit with a non-zero status, or to zero if all commands of the pipeline exit successfully.
set -u
This option causes the bash shell to treat unset variables as an error and exit immediately.
set -E
using -e without -E will cause an ERR trap to not fire in certain scenarios

https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/

The author also recommends to use -x, but I think it is way too verbose to be useful in the general use case.

According to https://dougrichardson.us/2018/08/03/fail-fast-bash-scripting.html, use

set -euo pipefail
shopt -s inherit_errexit

I like being explicit, and I like my code to fail fast, thus I suggest:

set -o errexit # -e
set -o errtrace # -E
set -o nounset # -u
set -o pipefail
shopt -s inherit_errexit

Fail Fast Bash Scripting

Fail Fast Bash Scripting

Summary Put this at the top of your fail-fast Bash scripts:

#!/bin/bash set -euo pipefail shopt -s inherit_errexit