Bash Scripting Cheat Sheet
The constructs my bootstrap and recovery scripts rely on, with what each one is for.
Overview
| Construct | Example | Purpose |
|---|---|---|
| Strict mode | set -euo pipefail |
stop on a failing command, an unset variable or a failing pipeline stage |
| Positional argument | NODE=$1 |
first argument given to the script |
| Root check | if [ "$EUID" -ne 0 ]; then echo "Run as root" >&2; exit 1; fi |
EUID is the effective user ID; 0 is root |
| Is a command installed | command -v sqv >/dev/null |
looks the name up in PATH, no hard-coded location |
| Heredoc | cat <<EOF > file |
write several lines; variables inside are expanded |
| Literal heredoc | cat <<'EOF' > file |
quoting the delimiter writes $VAR and $(...) as text |
| Indented heredoc | <<-EOF |
strips leading tabs (not spaces) from each line |
| Write a root-owned file | cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf |
sudo cat > file fails: the redirection runs as the calling user |
| Forward all arguments | "$@" |
passes every argument unchanged, spaces included |
| Replace the shell | exec /usr/bin/real-binary "$@" |
the wrapper becomes the target process, no extra shell left |
| Clean up on exit | trap cleanup EXIT |
runs on success, error and Ctrl+C (not on SIGKILL or power loss) |
| Allowed failure | cmd || true |
the script continues if cmd fails, whatever the reason |
| Command substitution | IP=$(hostname -I | awk '{print $1}') |
capture a command's output in a variable |
| Empty-string fallback | if [ -z "$IP" ]; then IP=127.0.0.1; fi |
-z is true for an empty string |
| Indirect variable | var="PASS_$NODE"; echo "${!var}" |
read the variable whose name is built at run time |
| Export a .env file | set -a; source .env; set +a |
every variable the file defines is exported to child processes |
Details
macOS Ships Bash 3.2
/bin/bash on macOS is version 3.2, which lacks associative arrays (declare -A), mapfile and case conversion (${var,,}), all added in Bash 4. A script meant to run on my Mac as well as on the Debian servers either sticks to 3.2 features, such as ${!var} above instead of a lookup table, or starts with #!/usr/bin/env bash and requires a newer Bash from Homebrew.
Wrapping a System Binary
cat > /usr/local/bin/tool <<'EOF2'
#!/usr/bin/env bash
exec /usr/bin/tool --extra-flag "$@" # the real binary, left untouched
EOF2
The literal heredoc keeps "$@" for the wrapper to expand at run time, and exec hands over to the real binary. Prefer a wrapper earlier in PATH (/usr/local/bin) to moving a packaged binary aside: the package manager's files stay intact. If you must replace the original, register the trap that restores it before moving it aside, so a failure while writing the wrapper still puts the real binary back; otherwise the script can exit with the binary missing and nothing to restore it.
Script Habits
- Print each stage (
echo "[1/5] Setting hostname..."), so a failure shows where it happened. - Edit lines in place with
sed -iinstead of appending with>>, and test thesedexpression on a copy first. - Use
apt-getin scripts (stable output) andaptinteractively.
References
- GNU Bash manual - the reference for every construct above.
- Bash Guide (Greg's Wiki) - a careful tutorial.
- ShellCheck - static analysis for shell scripts.
- Linux Administration MOC - hub for shell and Linux notes.
- set -e Misses a Failure Inside a Pipeline Unless pipefail Is Set - what strict mode does and doesn't catch.
- Idempotent Scripts Check the Current State Before Changing It - making scripts safe to re-run.
- Environment Variables Reach Child Processes Only When Exported - why
set -amatters when sourcing.env.