Bash Exit Codes
In Bash scripting, exit codes (or return codes) indicate the success or failure of a script or command. They are essential for debugging, automation, and creating robust scripts.
What Are Exit Codes?
An exit code is a numeric value returned by a command or script when it finishes execution. By convention:
- 0: Indicates success.
- Non-zero: Indicates failure or an error.
The exit code of the last executed command is stored in the special variable $?
.
How to Use Exit Codes
Check the Exit Code of a Command
Output (if directory exists):
Output (if directory doesn't exist):
Setting Exit Codes in Scripts
Use the exit
command to explicitly set an exit code in your script.
Example:
Execution:
Output:
Exit Code:
Common Exit Codes
Exit Code | Meaning |
---|---|
0 | Success |
1 | General Error |
2 | Misuse of shell builtins |
126 | Command invoked cannot execute |
127 | Command not found |
128 | Invalid argument to exit |
130 | Script terminated by Ctrl+C |
Example: Using Exit Codes in Automation
Basic Script Example
Execution:
Output (if connected):
Output (if not connected):
Using Exit Codes with Conditional Statements
Example:
Execution:
Output (if Git is installed):
Exit Code:
Best Practices for Exit Codes
Always Set an Explicit Exit Code: Avoid relying on the default exit code to ensure clarity.
Use Descriptive Exit Codes: Assign different codes for specific error conditions.
Handle Exit Codes in Scripts: Use
set -e
to automatically exit a script if any command fails.Document Exit Codes: Clearly define the meaning of each exit code in your script.
Debugging with Exit Codes
Trace Script Execution
Use set -x
to debug scripts and see the execution flow.
Trap Errors
Use trap
to handle errors and exit codes cleanly.
Conclusion
Understanding and using exit codes in Bash is vital for creating scripts that handle errors gracefully. By leveraging exit codes, you can write robust, maintainable, and automated solutions.
Let me know if you’d like further examples or advanced use cases!