Strict mode: set -euo pipefail

Updated November 1, 2026

By default bash keeps going after an error. In a script that is dangerous: one failed command and the rest runs on a broken state. set -euo pipefail makes the behaviour strict.

#!/usr/bin/env bash
set -euo pipefail
# -e  exit on the first error
# -u  error on an unset variable
# -o pipefail  error if any command in a pipeline fails

Sample output

$ cat deploy.sh
#!/usr/bin/env bash
cd /srv/app
echo done
$ ./deploy.sh
./deploy.sh: line 2: cd: /srv/app: No such file or directory
done
$ echo $?
0
$ sed -i "1a set -euo pipefail" deploy.sh
$ ./deploy.sh
./deploy.sh: line 3: cd: /srv/app: No such file or directory

Put this line right after the shebang. A full walk through each option is in Part III of the textbook.

Common mistakes

-e does not fire where you check the result yourself. Inside if command; then, after && and after ||, a failure is part of the logic, not a crash. The line grep -q nope /etc/hostname || echo alive prints alive and the script lives on, while the same grep on a line of its own kills it at once. That is where the feeling that strict mode works only sometimes comes from.

((i++)) kills the script at zero. A postfix increment returns the old value, which is 0 when i=0, and bash treats a zero arithmetic result as failure. Under set -e the script exits with code 1 and prints nothing at all: the line after ((i++)) simply never runs. Write i=$((i+1)) or ((i++)) || true.

-u hits script arguments. The line echo "arg is $1" in a script started with no arguments gives ./a.sh: line 3: $1: unbound variable and exit code 1. For an optional argument write ${1:-default value}; if the argument is required, test [ $# -eq 0 ] and print a clear hint yourself.

Used in

You need this in the lesson Bash: writing scripts.