How To Use Bash Exit Command.
In this article, we will cover the Bash exit built-in command and the exit statuses of the executed commands.
Each shell command returns an exit code when it terminates, either successfully or unsuccessfully.
By convention, an exit code of zero indicates that the command completed successfully, and non-zero means that an error was encountered.
The special variable $? returns the exit status of the last executed command:
The date command completed successfully, and the exit code is zero:
If you try to run ls on a nonexisting directory the exit code will be non-zero:
The status code can be used to find out why the command failed. Each command’s man page includes information about the exit codes.
When executing a multi-command pipeline, the exit status of the pipeline is that of the last command:
In the example above echo $? will print the exit code of the tee command.
Bash exit command
The exit command exits the shell with a status of N. It has the following syntax:
If N is not given, the exit status code is that of the last executed command.
When used in shell scripts, the value supplied as an argument to the exit command is returned to the shell as an exit code.
The commands’ exit status can be used in conditional commands such as if . In the following example grep will exit with zero (which means true in shell scripting) if the “search-string” is found in filename:
When running a list of commands separated by && (AND) or || (OR), the exit status of the command determines whether the next command in the list will be executed. Here, the mkdir command will be executed only if cd returns zero:
If a script ends with exit without specifying a parameter, the script exit code is that of the last command executed in the script.
Using just exit is the same as exit $? or omitting the exit.
Here is an example showing how to terminate the script if invoked by non-root user:
If you run the script as root, the exit code will be zero. Otherwise, the script will exit with status 1.
Each shell command returns an exit code when it terminates. The exit command is used to exit a shell with a given status.