Exit Codes & Debugging
Every BASH script must handle errors gracefully. Exit codes—numeric values returned by commands (0 for success, non-zero for failure)—are the foundation of robust error handling. By explicitly checking exit codes and leveraging built-in debugging tools, you can create scripts that self-diagnose and fail safely.
Checking Exit Codes with $?¶
Every command in BASH returns an exit code. Use $? to capture and inspect it.
Basic Checks¶
Conditional Logic¶
Chaining Commands¶
Use && (success) and || (failure) to chain commands:
Using set -e for Script Termination¶
The set -e option causes the script to exit immediately if any command returns a non-zero exit code.
Example Script¶
Caveats¶
set -eignores errors in subshells (e.g.,(...)) or commands with||.- Combine with
set -u(fail on undefined variables) for stricter validation:
Enabling Debugging with set -x¶
The set -x flag prints each command as it's executed, useful for tracing script flow.
Debug Output¶
Redirecting Debug Output¶
Use BASH_XTRACEFD to redirect debug messages to a file:
Key takeaways¶
- Always check exit codes with
$?to handle errors explicitly. - Use
set -eto terminate scripts on failures, but be aware of its limitations. - Enable debugging with
set -xto trace script execution and identify issues. - Combine
set -eandset -xfor rapid troubleshooting during development. - Prioritize clarity: let exit codes and debugging output guide your error resolution.