How do you use trap in shell scripting?

Why Interviewers Ask This

Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.

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.

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last Linux / Shell Scripting project, I used this when...' immediately makes your answer more credible and memorable.