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:
Syntax
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 pipefailis a common combo:-efor errors-ufor undefined variablespipefailso a failing command mid-pipeline is also caught.
Example: set -e and set -u
#!/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 try C/C++/Java/PHP code in the editor
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
- Using
set -eand expecting it to catch every failure, since it does not apply in conditions or pipelines. - Using
set -uand referencing an optional variable, which stops the script; use${var:-}. - Forgetting
set -o pipefail, so a failing command in a pipeline is ignored.
🔒
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Exit Codes and Checking $? Correctly
- set -e and set -u
- Error Handling
- set -e (Exit on Error) and Its Gotchas
- Logging
- set -u (Undefined Variables) and set -x (Trace Mode)
- Script Arguments with getopts
- trap ERR for Custom Error Handling
- Debug Mode (set -x)
- Writing a Custom Error/die Function
- Portability
- Validating Script Input and Arguments