Bash Exit Command and Exit Codes
3 min read
Often when 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.
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:
date &> /dev/null
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:
ls /nonexisting_dir &> /dev/null
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:
sudo tcpdump -n -l | tee file.out
In the example above
echo $? will print the exit code of the
exit command exits the shell with a status of
N. It has the following syntax:
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
. In the following example
grep will exit with zero (which means true in shell scripting) if the “search-string” is found in
if grep -q "search-string" filename then echo "String found." else echo "String not found." fi
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
command will be executed only if
cd returns zero:
cd /opt/code && mkdir project
If a script ends with
exit without specifying a parameter, the script exit code is that of the last command executed in the script.
#!/bin/bash echo "doing stuff..." exit
exit is the same as
exit $? or omitting the
Here is an example showing how to terminate the script if invoked by non-root user:
#!/bin/bash if [[ "$(whoami)" != root ]]; then echo "Only user root can run this script." exit 1 fi echo "doing stuff..." exit 0
If you run the script as root, the exit code will be zero. Otherwise, the script will exit with status
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.