bash set -e — exit script on error
Quick Answer
#!/usr/bin/env bash
set -euo pipefail
# -e exit on any non-zero exit code
# -u treat unset variables as errors
# -o pipefail pipelines fail on the first error, not just the last
Usage
Without set -e, bash scripts continue running after errors, which can cause silent data corruption or partial deploys.
Other causes & fixes
Allow a command to fail intentionally
set -e
# These patterns suppress the exit:
grep "pattern" file.txt || true
command_that_may_fail || echo "failed, continuing"
# Or temporarily disable
set +e
risky_command
set -e
set -u — catch undefined variables
set -u
echo "$UNDEFINED_VAR"
# bash: UNDEFINED_VAR: unbound variable → script exits
# Provide a default value to allow optional vars
echo "${OPTIONAL_VAR:-default}"
Trap errors for cleanup or logging
set -e
cleanup() {
echo "Error on line $1" >&2
}
trap 'cleanup $LINENO' ERR
# Or always run cleanup on exit
trap 'cleanup' EXIT
set -e does not catch all failures
set -e is ignored in some contexts: if conditions, while/until tests, || and && lists.
# This will NOT exit even with set -e
if failing_command; then
echo "success"
fi
Related