How do you use trap in shell scripting?

Answer

trap registers a command to run when the shell receives a signal or exits. Syntax: trap 'commands' SIGNAL. Key use case — cleanup on exit: trap 'rm -f /tmp/lockfile; echo "Exiting"' EXIT. The EXIT pseudo-signal fires whenever the script exits (normally or due to error). Handle Ctrl+C gracefully: trap 'echo "Interrupted"; exit 130' INT. trap '' SIGTERM ignores SIGTERM. trap - SIGNAL resets to default behavior. trap is essential for: removing temp files, releasing locks, sending notifications on failure, and ensuring cleanup in long-running scripts. Always set up trap early in the script before resources are acquired.