Understanding Bash Return Codes
In the world of Bash scripting, understanding return codes is crucial for writing robust and reliable shell scripts. Return codes, also known as exit codes or exit status, are numerical values that indicate the success or failure of a command or a script.
Bash Return Codes: The Basics
In Bash, the return code of a command or a script is stored in the special variable $?
. This variable holds the exit status of the last executed command. A return code of 0
indicates a successful execution, while any non-zero value represents an error or failure.
## Example: Checking the return code of the `ls` command
ls /path/to/directory
echo "The return code is: $?"
Understanding Common Return Codes
Bash follows a standard set of return codes, which are defined in the sysexits.h
header file. Here are some of the most common return codes and their meanings:
Return Code |
Meaning |
0 |
Successful execution |
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 Control-C |
255 |
Exit status out of range |
Understanding these common return codes will help you interpret the results of your shell scripts and handle errors more effectively.
Checking Return Codes in Bash
To check the return code of a command or a script, you can use the $?
variable immediately after the command's execution. This allows you to take appropriate actions based on the return code.
## Example: Checking the return code and taking action
command_to_execute
if [ $? -eq 0 ]; then
echo "Command executed successfully!"
else
echo "Command failed with return code: $?"
fi
By leveraging return codes, you can build more robust and error-handling shell scripts, which is the focus of the next section.