Result first: a four-line script whose cd failed (because BUILD_DIR was unset) kept going. It printed the wrong working directory, ran its "deploy" line, and exited 0. Adding one line, set -euo pipefail, made it stop on the first error with exit code 1: BUILD_DIR: unbound variable.
#!/usr/bin/env bash
set -euo pipefail
cd "$BUILD_DIR/out"
What each flag does (bash's own help set):
-
-e: "Exit immediately if a command exits with a non-zero status." -
-u: "Treat unset variables as an error when substituting." -
-o pipefail: "the return value of a pipeline is the status of the last command to exit with a non-zero status, or zero if no command exited with a non-zero status." Without it,false | truecounts as success.
Where -e still won't save you (GNU Bash manual): the shell does not exit when the failing command is part of the test in an if, inside a while/until condition, any command in a && or || list except the final one, or a command inverted with !. The demo shows if false; then …; fi carrying on under set -e. Don't treat strict mode as a substitute for checking the commands that matter.
For AI-assisted scripting: ask your agent to start every bash script with set -euo pipefail, and to quote variables. Then read any cd, rm or deploy line yourself before running it.
Do this now: run head -3 on your repo's .sh files and add strict mode to any that lack it. Then test each one, because scripts that relied on ignored errors will now stop.
Sources
- GNU Bash Reference Manual, "The Set Builtin" (fetched with curl; the web fetch tool was blocked with 403): https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html
From Penloom Studio's free AI lessons: penloomstudio.com
Top comments (0)