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
| Practice | Why |
|---|---|
#!/usr/bin/env bash | Portable interpreter |
set -euo pipefail | Fail on error/unset/pipe |
IFS=$'\n\t' | Safer splitting (optional) |
Quote "$var" / "$@" | Avoid splitting/globbing |
local in functions | No global leaks |
| Check deps | command -v |
| Prefer arrays | Lists with spaces |
| ShellCheck | Static 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"' EXITDry-run pattern:
run() {
if [[ "${DRY_RUN:-}" == 1 ]]; then
log "DRY: $*"
else
"$@"
fi
}⚠️ Pitfalls
- Blind
set -ewithout understanding exceptions inif/&&chains. - Parsing
ls,ps, or word-splitting filenames. - Hard-coding
/bin/bashwhenenvis 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.