How to use trap for signal handling in bash
· Category: Linux
Short answer
trap catches signals like INT, TERM, and EXIT to run cleanup code before a script terminates.
Steps
- Trap Ctrl+C:
trap "echo 'Interrupted'; exit 1" INT
- Cleanup on exit:
trap "rm -f /tmp/tempfile" EXIT
- Ignore a signal:
trap "" HUP
- Reset to default:
trap - INT
Tips
- Always clean up temporary files and locks with
trap. ERRtrap runs on any command failure whenset -Eis enabled.- Define cleanup functions for complex scripts.
Common issues
kill -9(SIGKILL) cannot be trapped.- Nested traps may overwrite each other; save and restore with variables.