In this article, we will discuss about the Bash exit built-in command and the exit code of the executed commands. Generally, at the time of writing Bash scripts, you will need to terminate the script when a certain condition is met or to take action based on the exit code of a command.
Exit Status
When any shell command terminates, it returns an exit
code, even successfully or unsuccessfully.
If the exit code is zero that means command completed successfully and non-zero means an error was encountered.
The special variable $?
returns the exit status of the last executed command:
date &> /dev/null
echo $?
The date command completed successfully, and the exit code is zero:
0
For example, if you try to navigate to nonexisting directory the exit code will be non-zero:
cd /no_dir &> /dev/null
echo $?
You can know the reason to command fail by the status code. You can get the information about the exit codes for each command in man page of each command.
When executing a multi-command pipeline, the exit status of the pipeline is that of the last command:
If you run the multi-command with pipe, the exit status will be of the last command in the pipeline.
mkdir -p test_dir2 | rm -r test_dir1
echo $?
In the example above echo $?
will print the exit code of the rm command.
Bash exit command
The exit command exits the shell with a status of N. It has the following syntax:
exit N
If N is not given, the exit status code is that of the last executed command.
Examples
At the time of writing script, often the exit status of command can be use as condition such as if
condition. In below example, grep will exit with zero if the given string found in filename
:
if grep -q "search-string" filename then
echo "String found."
else
echo "String not found."
fi
If you are running a list of commands separated by &&
or ||
operators, 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:
cd /work/project && mkdir test
If a script ends with exit without specifying a parameter, the script exit code is that of the last command executed in the script.
Conclusion
Each shell command returns an exit code when it terminates. The exit
command is used to exit a shell with a given status.
If you have any questions or feedback, feel free to leave a comment.