Bash Strict Mode & Error Handling
Advancedv1.0.0
Write robust Bash scripts with strict mode (set -euo pipefail), trap handlers for cleanup, proper error messages, and exit code conventions for production automation.
Content
Overview
Bash scripts silently continue after failures by default. Strict mode changes this behavior, making scripts fail fast on errors, undefined variables, and pipeline failures.
Why This Matters
- -Fail fast — catch errors immediately instead of cascading silently
- -No silent failures — unset variables cause errors, not empty strings
- -Pipeline safety — catch failures in any command of a pipeline
- -Production reliability — scripts behave predictably in CI/CD
Step 1: Enable Strict Mode
Step 2: Trap for Cleanup
Step 3: Error Reporting
Step 4: Exit Code Conventions
Step 5: Safe Variable Defaults
Best Practices
- -Always start with
set -euo pipefail - -Use
trap cleanup EXITfor guaranteed cleanup - -Use
${VAR:-default}for optional variables - -Use
${VAR:?error message}for required variables - -Use
die()function for fatal errors with messages - -Log to stderr (
>&2), output data to stdout
Common Mistakes
- -Not using strict mode (scripts continue after failures)
- -Not quoting variables (
$varinstead of"$var") - -Using
rm -rf $DIRwith unset DIR (deletes /) - -Not cleaning up temp files on error
- -Ignoring exit codes from critical commands
FAQ
Discussion
Loading comments...