shell

Shell / Bash

Script conventions, error handling, portability, and safety

Details

Language / Topic
_UUniversal
Category
Tooling

Rules

balanced
- Start every script with `set -euo pipefail` to fail on errors, undefined variables, and broken pipes.
- Always double-quote variables: `"$var"` — unquoted variables cause word splitting and glob expansion bugs.
- Use `[[ ]]` for conditionals instead of `[ ]` — it handles empty strings and pattern matching safely.
- Run `shellcheck` on all scripts before committing — it catches common bugs and portability issues.
- Use functions to organize reusable logic. Define a `main()` function and call it at the end: `main "$@"`.
- Use `trap 'cleanup' EXIT` to ensure temporary files and resources are cleaned up on exit or failure.
- Prefer `$(command)` over backticks for command substitution — it nests cleanly and is easier to read.
- Use `readonly` for constants and `local` for function variables to prevent accidental global mutations.
- Use meaningful exit codes: 0 for success, 1 for general errors, 2 for usage errors.