Code Reference

Scripts Best Practices

Bash · Reference cheat sheet

Scripts Best Practices

Bash · Reference cheat sheet


📋 Overview

Reliable bash scripts start with a clear shebang, strict mode, quoted expansions, and explicit error handling. Treat bash as glue: keep logic simple, prefer well-tested tools, and fail fast with useful messages.

🔧 Core concepts

PracticeWhy
#!/usr/bin/env bashPortable interpreter
set -euo pipefailFail on error/unset/pipe
IFS=$'\n\t'Safer splitting (optional)
Quote "$var" / "$@"Avoid splitting/globbing
local in functionsNo global leaks
Check depscommand -v
Prefer arraysLists with spaces
ShellCheckStatic analysis

Structure: constants → functions → main "$@" at the bottom. Log to stderr; keep stdout for data.

💡 Examples

Skeleton:

#!/usr/bin/env bash
set -euo pipefail

log() { printf '%s\n' "$*" >&2; }
die() { log "$*"; exit 1; }

need() { command -v "$1" >/dev/null || die "missing: $1"; }

main() {
  need jq
  [[ $# -ge 1 ]] || die "usage: $0 <file>"
  local file=$1
  [[ -f "$file" ]] || die "not a file: $file"
  jq . <"$file"
}

main "$@"

Safe temp files:

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

Dry-run pattern:

run() {
  if [[ "${DRY_RUN:-}" == 1 ]]; then
    log "DRY: $*"
  else
    "$@"
  fi
}

⚠️ Pitfalls

  • Blind set -e without understanding exceptions in if / && chains.
  • Parsing ls, ps, or word-splitting filenames.
  • Hard-coding /bin/bash when env is more portable.
  • Silent failures: always surface errors with context.
  • Running as root by default—drop privileges when possible.
  • Skipping ShellCheck (shellcheck script.sh) in CI.

On this page