Strict Mode with set -euo pipefail
Enable fail-fast behavior and understand exactly which errors each strict-mode flag catches and misses.
Why Bash Fails Silently by Default
By default, Bash keeps running even when commands fail. This leads to subtle, hard-to-debug disasters in production scripts.
Consider this script that tries to create a backup:
- A typo in a path causes
cpto fail - Bash ignores the failure and continues
- The script reports success even though data was never backed up
This is the silent failure problem. Strict mode solves it by making Bash behave like a compiled language: stop immediately when something goes wrong.
#!/usr/bin/env bash
# Without strict mode — dangerous default behavior
cp /important/data /backups/data # fails (path doesn't exist)
echo "Backup complete" # still prints — false confidence!
rm -rf /tmp/staging # still runs — potentially destructiveThe Three Core Flags: set -euo pipefail
Strict mode is enabled by placing this line near the top of every script:
set -euo pipefail
This activates three distinct guards:
-e— Exit immediately if any command returns a non-zero status-u— Treat unset variables as an error (instead of expanding to empty string)-o pipefail— A pipeline fails if any command in it fails, not just the last one
Together they form the standard defensive header for serious Bash scripts. Each flag catches a different class of bug.
#!/usr/bin/env bash
set -euo pipefail
echo "Strict mode is now active"
echo "Every command failure will abort the script"All lessons in this course
- Strict Mode with set -euo pipefail
- Trap Handlers for Cleanup and Signals
- Safe Temporary Files and Lock Directories
- Idempotent Scripts and Retry-with-Backoff Logic