Error Handling
Error handling is like checking that a cake really came out of the oven fine before serving it. Your script looks at whether each important step worked and reacts with a helpful message.
In this page:
Syntax
if ! command; then
echo "error message" >&2
exit 1
fi
command || handle_error
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Ignoring exit codes, so the script keeps going after a failure.
- Printing errors to standard output rather than
>&2. - Using
exitwith the wrong number, since 0 means success.
🔒
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