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

set -e and set -u

In this page:

  1. set -e and set -u

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, and 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

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.