The Three Lines of Strict Mode
By default, if line 4 of a 20-line bash script fails with an error, Bash happily continues executing line 5 through 20. If line 4 was `cd /backup_dir` and line 5 was `rm -rf *`, the script wipes your root folder.
Adding `set -euo pipefail` changes everything: `-e` exits immediately upon error, `-u` aborts if a variable is unset, and `-o pipefail` catches errors hidden inside pipes.
Guaranteed Resource Cleanup with Traps
If your script creates temporary scratch directories or starts background database tunnels, you must guarantee cleanup even if the script crashes or the user hits Ctrl+C.
Bash `trap` directives execute designated cleanup functions upon receiving `EXIT`, `ERR`, or `SIGINT` signals.
Step-by-Step Tutorial
Declare Strict Mode Header
Add `#!/usr/bin/env bash set -euo pipefail IFS=$"\n\t"` at the start of your script.
Define Idempotent Cleanup Trap
Create a `cleanup()` function that deletes `$TEMP_DIR` and register it with `trap cleanup EXIT ERR`.
Enforce Required Environment Variables
Validate inputs defensively: `: "${DATABASE_URL:?DATABASE_URL environment variable is required}"`.
Ready to Try It Yourself?
DocSwift processes everything directly on your device. Fast, safe, and completely free forever.
How helpful was this guide?
Rated 4.9 / 5 by 3,420+ users worldwide
Share with Colleagues & Friends
Help others protect their document privacy
Frequently Asked Questions
What does IFS=$'\n\t' do?
IFS stands for Internal Field Separator. By default, it splits on spaces, tabs, and newlines. Removing space from IFS prevents Bash from splitting filenames with spaces into separate loop iterations.
Can I temporarily disable "set -e" for a command that is expected to fail?
Yes! Either append `|| true` to the command (e.g. `grep pattern file.txt || true`), or wrap it: `set +e; failing_cmd; set -e`.