Proper Error Handling with trap and set -euo pipefail
Implement robust error handling in bash scripts using set flags, trap for cleanup, error reporting with line numbers, and safe variable expansion.
Prerequisites
- -Bash 4.0+
Steps
Enable strict mode
Add set flags at the top of every script to catch errors immediately.
-e exits on error, -u exits on unset variables, -o pipefail catches failures in pipes.
Add an error trap with line number reporting
Register a trap that reports the exact line number and command that failed.
Add a cleanup trap for temp files
Ensure temporary files and resources are cleaned up on exit, error, or interrupt.
EXIT traps run on both success and failure. ERR traps only run on errors. Use EXIT for cleanup and ERR for error reporting.
Use safe variable defaults
Prevent unset variable errors with default values and explicit checks.
${var:-default} provides a default without setting the variable. ${var:=default} also assigns the default.
Full Script
FAQ
Discussion
Loading comments...