Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Abort or exit a shell script if any command fails

Posted on May 27, 2023May 27, 2023 by admin

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

But the set -e command won’t work in the case of using pipes. Let’s see an example

set -e
p | echo "Hello"
echo "End of Script"

It will give the output

demo.sh: line 2: p: command not found
Hello
End of Script

The last command did got executed as seen from the above output

We have to additional use “-o pipefail” flag in addition to using the “-e” flag to tell bash that even if the command fails during pipe then also exit the script. Let’s see an example

set -eo pipefail
p | echo "Hello"
echo "End of Script"

Output

test.sh: line 2: p: command not found
Hello

In this case, the last command of echo did not execute and the script existed as expected.

Note: Check out our system design tutorial series System Design Questions

©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme