set -e and set -u
In this page:
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
#!/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
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