Published on

set -exu

set -exu is a shell built-in command (commonly used in bash scripts) that changes how the shell behaves. Each letter after - is an option.

Let’s break it down:


set -eExit on error

  • If any command returns a non-zero exit status, the script stops immediately.
  • Prevents scripts from continuing in a broken state.

Example

cp missing_file.txt /tmp
echo "This will NOT run"

If missing_file.txt doesn’t exist, the script exits before the echo.

📌 Exception: commands in if, while, until, &&, || are treated specially.


set -xExecution trace (debug mode)

  • Prints each command and its arguments to stderr before execution.
  • Very useful for debugging scripts.

Example output

+ echo Hello
Hello
+ ls /tmp

This shows exactly what the shell is executing.


set -uTreat unset variables as errors

  • Using an unset variable causes the script to exit immediately.
  • Helps catch typos and missing environment variables early.

Example

echo "$USERNAME"

If USERNAME is not set → script exits with an error.

You can safely handle defaults like this:

echo "${USERNAME:-default_user}"

Combined meaning of set -exu

When used together, it means:

Run in strict, safe, and debuggable mode

  • ❌ Stop on errors (-e)
  • 🔍 Show commands as they run (-x)
  • ⚠️ Fail on unset variables (-u)

This combination is very common in production-quality shell scripts and CI/CD pipelines.


Common alternative: set -Eeuo pipefail

You may also see:

set -Eeuo pipefail

Adds:

  • -E → traps work in functions/subshells
  • pipefail → pipelines fail if any command fails

TL;DR

set -exu

means:

“Fail fast, show me everything, and don’t tolerate sloppy variables.”