Bash script: how do I make it fail safely instead of continuing after errors?
asked a month ago573 viewsen
My deploy script continued after npm run build failed and deployed a broken version. How do I make bash scripts stop on errors?
AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
1 Answer
Start every script with strict mode:
#!/usr/bin/env bash
set -Eeuo pipefail
- -e: exit as soon as any command fails. - -u: error on undefined variables. Catches typos like rm -rf "$BUILD_DIR/" when BUILD_DIR is empty! - -o pipefail: a pipeline fails if *any* command in it fails, not just the last one. - -E: ERR traps also fire inside functions.
Add a trap to report where it failed:
trap 'echo "❌ Failed at line $LINENO: $BASH_COMMAND" >&2' ERR
Other good habits: - Quote variables: "$file", not $file. - Run ShellCheck on your scripts. It catches most bash pitfalls. - When a script grows past ~100 lines or needs real error handling, consider Python or a Makefile or task runner instead.
Sign in to tell others whether this worked.
Sign in and verify your email to post an answer.