Overview
If you want your shell script or shell file to exit in case any command in the shell file returns a non-zero value then you can use set -e at the start of the script.
It is sometimes annoying that one of the commands fails in your script, but the script continues without failing and causes unintentional output as it breaks the assumption in the rest of the script.
This is where the set -e comes to the rescue
Example
Let’s understand it with an example. We will first write a script without set -e. Below is a simple script. Let’s name it demo.sh In this script p is undefined and results in an error.
demo.sh
p
echo "End of Script"
Let’s run this script
sh demo.sh
Below will the output
demo.sh line 1: p: command not found
End of Script
Even though the script fails at line 1 but the last command of echo did got executed.
Let’s now the same script with set -e
demo.sh
set -e
p
echo "End of Script"
Run the script again. Below will be the output
demo.sh: line 2: p: command not found
With set -e the script exists immediately as soon as the first command fails. Therefore the subsequent command of echo is never executed
Note: Check out our system design tutorial series System Design Questions