The Bourne shell is the default shell for many Linux and Unix systems, and it provides a way to check the exit status of a command or a script. The exit status is a numerical value that represents the success or failure of the command or script. A value of 0 represents success, while any other value represents failure. Here are some examples of Bourne shell exit status codes:
- Successful command: If a command runs successfully, it returns an exit status of 0. For example, the following command returns a success exit status:
ls /home
- Unsuccessful command: If a command fails, it returns a non-zero exit status. The specific value depends on the type of error. For example, the following command returns a non-zero exit status:
ls /this/directory/does/not/exist
- Testing exit status: You can use the
echo
command and the special variable$?
to display the exit status of the last command. For example:ls /home
echo $?
This will output
0
to indicate that thels
command was successful. Alternatively, if you run:ls /this/directory/does/not/exist
echo $?
This will output a non-zero value (usually 1) to indicate that the
ls
command failed. - Checking exit status in a script: You can use exit statuses to control the behavior of a script. For example, you can check whether a command ran successfully and take different actions based on the result. Here’s an example:
rm /tmp/file.txt
if [ $? -eq 0 ]; then
echo "File deleted successfully"
else
echo "Failed to delete file"
fi
In this example, the
rm
command is executed to delete a file. If the command runs successfully, the script will print “File deleted successfully”. If it fails, the script will print “Failed to delete file”. The$?
variable is used to check the exit status of the previous command (in this case,rm
).
These are just a few examples of how you can use exit statuses in the Bourne shell. By checking the exit status of commands, you can automate scripts and make them more robust.