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.
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
-eexits when a command fails (with exceptions such as conditions inif).-utreats unset variables as errors (catches typos).-o pipefailmakes a pipeline fail if any command in it fails, not only the last.
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.
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?
Pipes run in parallelA pipeline fails if any command in it failsErrors are printed to a fileThe script retries failed commands
Show answer
Answer: A pipeline fails if any command in it fails