Bash Trap Not Catching Errors Fix
In this tutorial, you'll learn about Bash Trap Not Catching Errors Fix. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Bash trap does not catch errors when the signal name is misspelled, the trap is set after the error occurs, or set -e interferes with the ERR trap.
The Wrong Way
#!/bin/bash
trap "echo Error occurred" ERR
set -e
false
echo "This never runs"
Output:
(script exits silently without printing "Error occurred")
When set -e is active, the script exits before the ERR trap is triggered.
The Right Way
#!/bin/bash
set -e
trap "echo Error on line $LINENO" ERR
false
echo "This never runs"
Output:
Error on line 5
The ERR trap fires before the script exits due to set -e.
Step-by-Step Fix
1. Use correct signal names
trap cleanup EXIT # runs on script exit
trap cleanup ERR # runs on any error
trap cleanup INT # runs on Ctrl+C
2. Set trap before potential errors
trap 'echo "Error at line $LINENO"' ERR
# now any error will trigger the trap
3. Use trap with functions
cleanup() {
echo "Cleaning up..."
rm -f /tmp/tempfile
}
trap cleanup EXIT
4. Trap inside functions
myfunc() {
trap 'echo "Error in myfunc"' ERR
false
}
5. Use trap with multiple signals
trap 'echo "Script interrupted"; exit 1' INT TERM
trap 'echo "Script exiting"; cleanup' EXIT
Prevention Tips
- Set traps at the top of the script, before any commands run.
- Use single quotes in trap to prevent premature variable expansion.
- Use
$LINENOin the trap command to report the error location. - Use
ERRtrap for error handling,EXITfor cleanup,INTfor Ctrl+C. - Test the trap by intentionally causing an error during development.
Common Mistakes with trap error
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world BASH code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro