Error Handling
In this page:
Error Handling
Beyond set -e, scripts should explicitly check the exit status of critical commands (via $? or directly in an if) and respond appropriately, such as printing a message and exiting. Wrapping risky sections and checking results makes failure modes intentional rather than accidental. Good error handling makes a script fail loudly and clearly instead of silently producing wrong results.
Note: Print error messages to stderr with >&2 so they don't get mixed into a script's normal output stream.
Example: Error Handling
#!/bin/bash
run_task() {
false # simulate a failing command
}
(
if run_task; then
echo "Task succeeded"
else
echo "Error: task failed" >&2
exit 1
fi
)
echo "Subshell exited with status $?, script continues"
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Exit Codes and Checking $? Correctly
- set -e and set -u
- Error Handling
- set -e (Exit on Error) and Its Gotchas
- Logging
- set -u (Undefined Variables) and set -x (Trace Mode)
- Script Arguments with getopts
- trap ERR for Custom Error Handling
- Debug Mode (set -x)
- Writing a Custom Error/die Function
- Portability
- Validating Script Input and Arguments