🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Strict Mode

Strict mode is a set of Bash options that makes a script stop at the first mistake. It turns three quiet problems into loud stops.

set -e stops a subshell at the first failure

The subshell turns -e on, then runs a failing command. The line after the failure never prints, and the outer script reports status 1.

(set -e
echo "before"
false
echo "after")
echo "subshell status: $?"

-e stays quiet in tests and after ||

The failing command sits in an if test and after ||. Neither spot stops the script, so the final line still prints.

set -e
false || echo "or branch ran"
if false; then
  echo "then branch"
else
  echo "condition failed, script alive"
fi
echo "still running"

pipefail catches a failure in the middle of a pipeline

Without pipefail, the pipeline reports the last command, which succeeds. With pipefail on, the same pipeline reports status 1.

false | true
echo "plain status: $?"
set -o pipefail
false | true
echo "pipefail status: $?"

Example

#!/bin/bash
set -euo pipefail
name="backup"
echo "Starting $name"
echo "Count is $count"
echo "This line never runs"

Key points

  • set -e: stop the script when a command fails.
  • set -u: stop the script when it reads an unset variable.
  • set -o pipefail: make a pipeline fail when any part fails.
  • set -euo pipefail: the common one-line form that turns all three on.
  • -e limit: a failing command in an if test does not stop the script.
  • -u limit: reading an unset variable stops the script, even where empty text would do.

In this example, the script turns strict mode on, then sets a name. The next echo prints the starting line. The following echo reads an unset variable, so -u stops the script at once. The last line never runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A script runs with set -e. A command fails inside an if test. What happens?