Bash script: how do I make it fail safely instead of continuing after errors?

posée a month ago575 vuesen

0

My deploy script continued after npm run build failed and deployed a broken version. How do I make bash scripts stop on errors?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée a month ago

1 réponse

9
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered a month ago

Sign in and verify your email to post an answer.