Robust Scripts: set -euo pipefail, trap & shellcheck
Making scripts fail fast and clean up after themselves, instead of continuing after an error.
By default Bash keeps running after a command fails, which can turn one small error into a disaster (rm -rf "$DIR/" with DIR empty...). Strict mode makes scripts stop at the first unexpected problem, and trap guarantees cleanup.
Strict mode in action
set -e exits on any unhandled failing command, -u on unset variables, -o pipefail when any part of a pipeline fails.
trap cleanup EXIT runs cleanup however the script ends — normally, on error, or interrupted.
Failures you expect are handled explicitly: in an if, or with || true.
Using UNDEFINED_SETTING stops the script with 'unbound variable', and cleanup still runs.
More habits
rm -rf "$BUILD_DIR/"* # BUILD_DIR unset -> deletes from / rm -rf "${BUILD_DIR:?BUILD_DIR is not set}/"*
With an empty variable the path becomes /*. ${var:?} (or set -u) stops the script instead.
What does set -o pipefail change?
A pipeline's exit status becomes that of the last command that failed (instead of only the last command), so failures early in the pipeline are not hidden.