Handle failures explicitly
An exit status is a small integer describing the outcome of a command; zero means success, not necessarily that useful data was produced. Decide which failures are expected and which prevent further work. Put dependent work after a successful check. Capture a failed status in the else branch immediately, before logging. Use return inside a function and exit at a standalone entry point. A function should document its status contract and write diagnostic messages separately from its data. A negated condition reverses the status, so do not capture the original failure after !. These examples use synthetic operations, not real services. The first demonstration deliberately handles the error and ends with status zero. If the caller must see the failure, use an explicit return or exit with the saved status. A diagnostic alone does not propagate it.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Guard dependent work
prepare() { return 7; }if prepare; then printf 'publish\n'else rc=$? printf 'blocked: %s\n' "$rc" >&2fiprintf 'finished checking\n' Expected stdout:
finished checkingExpected stderr:
blocked: 7The failure is handled intentionally; publish is skipped. The final printf succeeds.
Propagate failure from a function
build() { return 4; }main() { build || return "$?" printf 'artifact ready\n'}mainrc=$?printf 'main=%s\n' "$rc" Expected stdout:
main=4The right side of || runs only if build fails. Return preserves its status and skips the success message.
Negation changes status
if ! (exit 7); then printf 'negated=%s\n' "$?"fiif (exit 7); then :else printf 'original=%s\n' "$?"fiExpected stdout:
negated=0original=7A successful negation has status zero; the ordinary else branch retains the original failure.
Common mistakes
Avoid running false; printf ...; status=$? and expecting the status of false. Avoid if ! task; then rc=$?; ... when the original status matters. Do not retry every nonzero status blindly.
Practice
Write a function that returns 4 for missing data and 0 for valid data. Check both cases, keep diagnostics on stderr and prove that dependent work only runs on success.
Next: pipefail and pipeline failures