← Back to Bash Course | Chapter 12: Error Handling & Debugging | Lesson 2 of 12

set -e and set -u

set -e is like a fire alarm that stops the game as soon as something goes wrong, and set -u shouts if you use a label that you never filled in.

In this page:

  1. set -e and set -u
Syntax
bash
set -e    # exit on error
set -u    # error on unset variables

set -e and set -u

set -e makes a script exit immediately if any command fails (returns non-zero), instead of continuing and potentially causing cascading damage.

set -u makes referencing an undefined variable an error instead of silently expanding to an empty string, catching typos early. Combining both near the top of a script is a widely recommended defensive habit.

Note:
  • set -euo pipefail is a common combo:
  • -e for errors
  • -u for undefined variables
  • pipefail so a failing command mid-pipeline is also caught.

Example: set -e and set -u

bash
#!/bin/bash
set -eu

echo "Starting script with strict mode enabled"
name="Bash"
echo "Hello, $name!"
# echo "$undefined_var" would cause an immediate error under set -u
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using set -e and expecting it to catch every failure, since it does not apply in conditions or pipelines.
  2. Using set -u and referencing an optional variable, which stops the script; use ${var:-}.
  3. Forgetting set -o pipefail, so a failing command in a pipeline is ignored.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.