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

poze a month ago571 gadeen

0

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

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze a month ago

1 Repons

9
✓
✓ Repons yo aksepte

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.

Konekte pou di lòt moun si li te mache.

answered a month ago

Sign in and verify your email to post an answer.