Bash Error Handling
Error handling is code that spots a failure and stops the script with a clear message. It keeps a small problem from turning into silent damage later.
A die function stops the script with a clear message
The guard checks for a file that does not exist. The die function prints the error and exits, so the success line never prints.
die() {
echo "Error: $1" >&2
exit 1
}
[ -f data.txt ] || die "data file missing"
echo "data file ready"An ERR trap reports a failure without stopping the script
The trap prints a fixed line whenever a command fails. The failing command does not stop the script here, so the last line still prints.
trap 'echo "a command failed"' ERR
false
echo "script continues"An EXIT trap always runs cleanup at the end
The trap prints a cleanup line when the script ends. It runs after the last work line, even on a normal finish.
trap 'echo "cleanup done"' EXIT
echo "work done"Example
#!/bin/bash
cleanup() {
echo "Removing temp work"
}
trap cleanup EXIT
die() {
echo "Error: $1" >&2
exit 1
}
printf 'one\ntwo\n' > data.txt
[ -f data.txt ] || die "data file missing"
echo "Data file ready"
echo "Lines: $(grep -c '' data.txt)"Key points
- die: a small function that prints an error and exits at once.
- Exit code: a number a script returns; zero means success and anything else means failure.
- ERR trap: a handler that runs when a command fails.
- EXIT trap: a handler that runs when the script ends, for cleanup.
- Fail fast: stop at the first real problem instead of guessing onward.
- Clear message: an error line that names what went wrong.
In this example, the script sets a cleanup trap, then defines a die function. It writes a small data file and checks that the file exists. The guard would call die if the file were missing. The script prints the ready line and the line count, then the EXIT trap prints the cleanup line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does an EXIT trap do?