set -euo pipefail
set -euo pipefail in Bash ensures scripts fail fast on errors (-e), treat unset variables as errors (-u), and propagate failures through pipelines (pipefail). It’s a best practice for writing safe, predictable, and robust Bash scripts.
Bash scripts are powerful, but they can fail silently, leaving subtle errors unnoticed and causing unexpected behavior. By enabling set -euo pipefail, you transform your script into a defensive, error-aware program. Each option serves a clear purpose: it stops execution on failures (-e), catches undefined variables (-u), ensures typos and misused variables are flagged, and makes pipelines fail if any command within them fails (-o pipefail).
Together, these four settings make your scripts safer, more predictable, and far less prone to hidden errors.
1. set -e
- Exits the script immediately if any command returns a non-zero status.
- Prevents continuing execution after a failed command.
- Example:
set -e
false # Script stops here
echo "Won't run"
2. set -u
- Treats unset variables as errors.
- Helps catch typos and prevents using undefined values.
- Example:
set -u
echo $UNDEFINED_VAR # Script exits here
3. set -o pipefail
- Ensures a pipeline fails if any command fails, not just the last one.
- Example:
set -o pipefail
false | true # Script exits due to 'false'
4. Combining them
Using all three together is the standard for robust scripts:
#!/bin/bash
set -euo pipefail
echo "Safe script start"
set -euo pipefail is a cornerstone of safe Bash scripting. It provides early error detection, prevents silent failures, and ensures predictable behavior. Any production-ready or critical script should use it to avoid subtle bugs and data corruption.
Thanks for checking in, and we hope this was helpful!