Exit codes, also known as return codes or exit statuses, are numeric values that indicate the success or failure of a command or script in Unix-like operating systems, including shell scripting. Every command or script execution sets an exit code, which can be checked to determine the outcome of the operation. Exit codes are particularly useful for error handling and decision making in shell scripts.
Here’s how exit codes work and how you can use them to handle errors:
Exit Code Conventions:
- An exit code of
0
generally indicates success or that the command completed without errors. - Non-zero exit codes typically indicate various types of errors or failures.
- Different commands and scripts might use specific non-zero exit codes to indicate different types of errors. However, there are some common conventions:
- Exit code
1
: General or unspecified error - Exit code
2
: Misuse of shell commands (e.g., incorrect syntax) - Exit code
126
: Command not executable - Exit code
127
: Command not found - Exit code
128
: Invalid exit argument or signal termination - Exit code
130
: Command terminated by Ctrl+C (usually for interactive shells) - Exit code
255
: Command or script execution failed
Using Exit Codes for Error Handling:
In shell scripting, you can use exit codes to determine whether a command or script was successful and then take appropriate actions based on that information. Here’s how you can do it:
- Checking Exit Codes with
if
Statements:
You can use theif
statement to check the exit code of a command or script and perform different actions accordingly.
if command; then
echo "Command was successful."
else
echo "Command failed."
fi
For example, if you’re checking the existence of a file:
if [ -f "myfile.txt" ]; then
echo "File exists."
else
echo "File does not exist."
fi
- Storing Exit Codes:
You can store the exit code of a command in a variable for later use.
command
exit_code=$?
echo "Exit code: $exit_code"
- Using Exit Codes in Logical Expressions:
You can use exit codes in logical expressions to conditionally execute commands.
command1 && command2 # Run command2 only if command1 succeeds
command1 || command2 # Run command2 only if command1 fails
- Exiting Scripts with Specific Exit Codes:
Within your own scripts, you can set specific exit codes using theexit
command to indicate certain outcomes.
if [ condition ]; then
exit 0 # Success
else
exit 1 # Failure
fi
By leveraging exit codes, you can make your scripts more robust and capable of handling various scenarios, such as different types of errors or conditions that require specific actions.