Bash Exit Command and Exit Codes

Published on

3 min read

Bash Exit

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.

Exit Status

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/nullecho $?

The date command completed successfully, and the exit code is zero:

0

If you try to run ls on a nonexisting directory the exit code will be non-zero:

ls /nonexisting_dir &> /dev/nullecho $?
2

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.outecho $?

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:

exit N

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.

Examples

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:

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 mkdir 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.

~/script.sh
#!/bin/bash

echo "doing stuff..."

exit

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:

#!/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 1.

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.