What Does “set -e” In Bash?

Linux bash provides a very good programming environment where scripts and functions can be created and executed. If there is an error related to a script file or function bash ignores these errors by default. But if we rely on the script or function execution and get detailed information about the result the set -e command can be used to stop the execution of the script or function and return non-zero error code. By default bash functions and scripts returns 0 if they complete their execution successfully without any error or problem. If there is an error the error code is provided to provide detailed information about the error.

Exit Script If There Is An Error

In order to exit from a script or function if there is an error, we will use the set -e like below. In the following example, we set exit if there is an error. at the start of the script. So the “mkdir /root/test” raise an error as there is no root permission and it can not be created. As a result, the line echo "Progress..." can be executed and printed to the terminal.


set -e

mkdir /root/test

echo "Progress..."
$ ./test.sh 
mkdir: cannot create directory ‘/root/test’: Permission denied

Read Error Code

As the script is exited with an error there is an error code that describes the error. Bash provides the $? variable in order to store the latest script execution status and it will be an error code if the last script execution is stopped with an error. The error code can be read with the following line.

$ echo $?

Disable Exit If There Is An Error

The exit on an error can be disabled by using set +e command. Actually this is the default behaivour of the bash environment.

$ set +e

Leave a Comment