Understanding Exit Codes
In the world of Linux shell scripting, exit codes play a crucial role in determining the success or failure of a script's execution. Exit codes are numeric values returned by a command or a script when it completes, indicating the outcome of the operation.
What are Exit Codes?
Exit codes are integers ranging from 0 to 255, where 0 typically represents a successful execution, and non-zero values indicate various types of errors or exceptions. Each exit code has a specific meaning, and understanding these codes is essential for effective error handling and troubleshooting in your shell scripts.
Accessing Exit Codes
In a shell script, you can access the exit code of the previously executed command or script using the special variable $?
. This variable holds the exit code of the last executed command, allowing you to check the result and take appropriate actions based on the value.
## Example
ls /non-existent-directory
echo "The exit code is: $?"
In the example above, the ls
command will fail to find the non-existent directory, and the exit code will be a non-zero value (typically 1), which can be accessed using the $?
variable.
Common Exit Codes
While there are many possible exit codes, some of the most commonly used ones are:
Exit Code |
Meaning |
0 |
Successful execution |
1 |
General error |
2 |
Misuse of shell built-in |
126 |
Command invoked cannot execute |
127 |
Command not found |
128+n |
Fatal error signal "n" |
Understanding these common exit codes will help you write more robust and error-handling shell scripts.