Understanding Exit Statuses
Introduction to Understanding Exit Statuses
Welcome! In this lesson, we will explore the concept of exit statuses in shell scripts. An exit status indicates whether a command was successful or if an error occurred. This lesson will guide you through the basics of exit statuses, including how to check them, handle errors, and use them to control the flow of your scripts.
Let's get started!
The Basics of Exit Statuses
In the Unix-like operating system, every command returns an exit status when it finishes executing. This exit status is a number where:
0indicates success.- Any non-zero value indicates an error (the specific number can provide information about the kind of error).
To check the exit status of a command, we use the special variable $?.
Suppose we have a directory called projects. Inside projects, there is a file p1.txt. We can observe the exit status for ls commands as follows:
Here's an example:
- The
ls projectscommand lists the contents of theprojectsdirectory, which is justp1.txt. Since it is a valid directory, the exit status is0. - The
ls nonexistent_directorycommand attempts to list a directory that does not exist, resulting in an error. The exit status is a non-zero value, typically2.
The output of the code is:
The following error message is also output:
We can see that the successful ls command has an exit status of 0 (success). The unsuccessful ls command has an exit status of 2 and outputs a descriptive error message.
The `exit` Command
The exit command in a shell script is used to terminate the script and optionally provide an exit status. The exit status is a numeric value that indicates the result or outcome of the script's execution. By convention, an exit status of 0 indicates that the script completed successfully without any errors.
Any non-zero exit status indicates that the script encountered an error or abnormal condition. Common non-zero exit statuses include:
- 1: General errors.
- 2: Misuse of shell builtins (according to the Bash documentation).
- 126: Command invoked cannot execute.
- 127: Command not found.
- 128: Invalid argument to exit.
- 130: Script terminated by Control-C.
When used in a script, you can specify the exit status as an argument to the exit command, like exit 1, to indicate a specific type of error. If no argument is provided to exit, the script will terminate with the status of the last executed command.
Sometimes, you might want to exit your script with a specific status. You can use the exit command followed by a status code. For example:
exit 42 terminates the script and returns status 42 to the calling shell or process. This calling shell or process can access this exit status using $?.
