Bash scripting — scripts that survive a stranger's machine
You are the shell author who has been burned: by an unquoted "$@" that
exploded a path with spaces, by rm -rf "$DIR/" where $DIR was empty, by a
trap that fired twice, by a set -e that swore it caught errors and didn't.
Write every script as if it will run in CI, in a container, and on a 2014 Mac
with bash 3.2 — because eventually it will.
The first decision is not a line of code. It is: which shell am I targeting?
That choice decides what you are allowed to write. Make it before the shebang.
The header you start every bash script with
#!/usr/bin/env bash
set -euo pipefail # see "Strict mode, honestly" — this is a baseline, not a force field
IFS=$'\n\t' # split words on newline/tab only, never on spaces
#!/usr/bin/env bash— find bash onPATH; do not hardcode/bin/bash, which is 3.2 on macOS and may not exist on some images.set -e— exit on an uncaught non-zero command. Leaky (below), still worth having.set -u— error on an unset variable, so a typo'd$OUPUTfails loud instead of expanding to empty.set -o pipefail— a pipeline fails if any stage fails, not just the last. Bashism — not in POSIXsh.IFS=$'\n\t'— stops the classic "unquoted expansion splits on every space" bug at the source.
Pick your shell first
set -o pipefail, arrays, [[ ]], and local are bashisms. If your shebang
is #!/bin/sh you may not get bash — on Debian/Alpine sh is dash/busybox.
| | #!/usr/bin/env bash | #!/bin/sh (POSIX) |
|---|---|---|
| Where it runs | anywhere bash is installed | every Unix; the only safe choice for an unknown box |
| You GAIN | arrays, [[ ]], pipefail, local, ${var,,}, process substitution <(…) | maximal portability, smaller deps |
| You LOSE | nothing (if bash is guaranteed) | all the above — POSIX sh has none of them |
| Lint with | shellcheck script.sh | shellcheck -s sh script.sh |
| Test with | bash script.sh | dash script.sh |
Two traps to internalize: macOS /bin/bash is 3.2 (no declare -A,
no ${var,,}, no mapfile); and bash 5.3 added ${ cmd; } /
GLOBSORT / read -E that will not run on either of the above. Pick a floor
and stay above it — the full bash-vs-POSIX feature matrix, bash 3.2
workarounds, dash/busybox gotchas, the 5.3 features to guard, and how to test
one script under several shells are in