Bash Scripting Cheat Sheet

In progress Linux

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 -i instead of appending with >>, and test the sed expression on a copy first.
  • Use apt-get in scripts (stable output) and apt interactively.

References