← cogloom · All free lessons

cogloom · Free lesson

The AI-written shell script that ran from the wrong folder and exited 0: `set -euo pipefail`, and where it still won't save you

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 | true counts 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


Also on dev.to: read this lesson on dev.to. More free lessons: cogloom lessons index.