Patterns#

A handful of patterns make Bash scripts safer and more maintainable.

Strict Mode#

Fail fast on errors, undefined variables, and broken pipes:

$ #!/usr/bin/env bash
$ set -euo pipefail
$ IFS=$'\n\t'

Cleanup#

Use trap to release resources whether the script succeeds or fails:

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

Argument Parsing#

For short flags, use getopts. For long flags, hand-roll a loop:

$ while [[ $# -gt 0 ]]; do
  $ case "$1" in
    $ --name)  name="$2"; shift 2 ;;
    $ --force) force=1; shift ;;
    $ --)      shift; break ;;
    $ *)       echo "unknown: $1" >&2; exit 2 ;;
  $ esac
$ done

Quoting#

Always quote expansions to preserve spaces and avoid globbing:

$ for f in "$@"; do
  $ mv -- "$f" "/tmp/$f"
$ done

Subshells & Pipes#

Each side of a pipe runs in its own subshell, so variables set on the right don’t leak left. Use shopt -s lastpipe (with job control off) to keep the last segment in the parent shell.