Technology

Bash Scripting Habits That Prevent 3 a.m. Pages

Five small habits — strict mode, quoting, logging and more — that make shell scripts fail loudly and safely instead of silently.

Abstract illustration of a script running through server panels

Most shell scripts start as a quick fix and end up running in production for years. A few habits make the difference between a script that fails safely and one that quietly does the wrong thing.

1. Start every script in strict mode

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
  • -e stops on the first failing command.
  • -u treats unset variables as errors.
  • -o pipefail makes a pipeline fail if any part of it fails.

2. Quote every variable

Unquoted variables split on spaces and expand wildcards. rm -rf $DIR/* with an empty $DIR is a very bad day. Write "$DIR" every time.

3. Log what you’re doing

log() { printf '%s [%s] %s\n' "$(date -Is)" "${0##*/}" "$*" >&2; }
log "Starting backup of $SOURCE"

4. Clean up with a trap

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

5. Run ShellCheck

ShellCheck catches most quoting and logic mistakes before they reach a server. Add it to your CI pipeline and let it nag you.

Keep Reading

Related articles

Let’s Talk

Let’s build something reliable together

Open to consulting, speaking and collaboration across SAP administration, cloud infrastructure and cybersecurity — questions are always welcome.