Bash Tutorial · Bash Scripting · Lesson 22 of 30

Bash Error Handling: set -euo pipefail and trap

Make scripts stop on errors, catch failures in pipelines, and clean up with trap.

Create a free account to save this page, take notes and track your progress. Sign in

Exit codes

Every command returns an exit status: 0 success, anything else failure. $? holds the last one.

Strict mode

Put this at the top of scripts:

set -euo pipefail
  • -e exits when a command fails (with exceptions such as conditions in if).
  • -u treats unset variables as errors (catches typos).
  • -o pipefail makes a pipeline fail if any command in it fails, not only the last.
Strict mode stops early
cat > strict.sh <<'EOF'
set -euo pipefail
echo "step 1"
grep -q needle missing.txt | sort
echo "never printed"
EOF
bash strict.sh 2>&1 || echo "strict.sh failed with status $?"
bash -c 'set -u; echo "value: $UNDEFINED"' 2>&1 | sed 's/^.*: line [0-9]*: //' || true

Output

step 1
grep: missing.txt: No such file or directory
strict.sh failed with status 2
UNDEFINED: unbound variable

Run this on your computer — see “Get Started” for setup.

Cleaning up with trap

trap 'commands' EXIT runs on exit, whether the script succeeds or fails: ideal for temporary files.

trap cleans up even on failure
cat > job.sh <<'EOF'
set -euo pipefail
workdir=$(mktemp -d)
trap 'rm -rf "$workdir"; echo "cleaned up"' EXIT
echo "working in a temp dir"
echo data > "$workdir/file"
false
EOF
bash job.sh || echo "job.sh exited with $?"

Output

working in a temp dir
cleaned up
job.sh exited with 1

Run this on your computer — see “Get Started” for setup.

Test yourself

What does set -o pipefail change?

  1. Pipes run in parallel
  2. A pipeline fails if any command in it fails
  3. Errors are printed to a file
  4. The script retries failed commands
Show answer

Answer: A pipeline fails if any command in it fails

Was this page helpful?