13. Error Handling#
This chapter focuses on making scripts dependable: exit codes, shell options, traps, defensive checks, logging, and error redirection.
Exit codes: Use command status values to decide what a script should do next.
Shell options: Enable stricter behavior when failures should stop execution.
Traps: Run cleanup or diagnostic code when signals or errors occur.
Defensive scripting: Validate assumptions before commands cause damage.
Isolation: Use subshells and process substitution when temporary context should not leak.
Logging: Record useful information for debugging and maintenance.
Chapter Video
How to Debug a Bash Script (7:23) by ProgrammingKnowledge
Hosted on YouTube; property of its original creator, embedded here for educational reference only.
Learning Objectives
By the end of this chapter, you will be able to:
Interpret exit codes and propagate failures intentionally.
Use shell options and traps to control failure behavior.
Use subshells and process substitution deliberately in defensive scripts.
Apply defensive scripting practices to risky operations.
Log messages and redirect errors for diagnosis.
Chapter Flow
Glossary
# |
Term |
Explanation |
|---|---|---|
1 |
Exit code |
A numeric command result where |
2 |
Error propagation |
Passing failure information from one command or function to its caller. |
3 |
|
The exit status of the most recently completed foreground command. |
4 |
|
A shell option that exits on some unhandled command failures. |
5 |
|
A shell option that treats unset variables as errors. |
6 |
|
An option that makes pipeline failure visible when any command fails. |
7 |
Trace mode |
Debug output enabled with |
8 |
|
A Bash builtin that runs commands when signals or selected events occur. |
9 |
Signal |
A process notification such as |
10 |
Cleanup handler |
Code that removes temporary files or restores state before exit. |
11 |
Defensive scripting |
Writing checks that prevent unsafe assumptions from becoming failures. |
12 |
Input validation |
Checking external values before using them. |
13 |
Precondition |
A condition that must be true before a command or function can proceed. |
14 |
Temporary file |
A short-lived file used while a script is running. |
15 |
Log level |
A category such as info, warning, or error for recorded messages. |
16 |
stderr |
The standard stream for diagnostics and errors. |
17 |
Error redirection |
Routing error output to a file, stream, or command. |
18 |
ShellCheck |
A static analysis tool that flags common shell script problems. |
19 |
Rollback |
A recovery action that restores a previous safe state. |
20 |
Idempotence |
The property that repeating an operation has the same effect as doing it once. |
21 |
|
A Bash builtin for enabling or disabling shell options. |
22 |
Subshell |
A child shell environment created for grouped commands or pipelines. |
23 |
Process substitution |
Bash syntax such as |
24 |
|
Environment variable that records enabled shell options. |