ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Bash Shell Scripting Tutorial• 7 min read

Defensive Shell Scripting: set -euo pipefail

Writing bulletproof automation scripts that fail immediately on bugs

By default, Bash continues executing subsequent commands even if an earlier command crashes or references an unset variable! "Unofficial Bash Strict Mode" enforces immediate failure.

The Unofficial Bash Strict Mode (`set -euo pipefail`)

set -e: Exit immediately if any command exits with a non-zero status.

set -u: Treat unset variables as errors and exit immediately, preventing catastrophic bugs like rm -rf /tmp/$UNSET_DIR from expanding to rm -rf /!

set -o pipefail: Prevents pipeline errors from being masked. The pipeline returns the exit status of the last command to fail.

Production Strict Mode Boilerplate
#!/usr/bin/env bash
# Enforce strict mode for production reliability
set -euo pipefail
IFS=$'\n\t'

echo "Deploying production release..."

BACKUP_DIR="/backups/$(date +%Y%m%d)"
mkdir -p "$BACKUP_DIR"

# If this command fails, the entire script halts immediately!
rsync -avz /var/www/html/ "$BACKUP_DIR/"

echo "Backup verified successfully."
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Why is `set -u` included in strict defensive Bash scripts?