Execute commands when the shell receives signals or exits.
low risk
trap registers commands to run when specific signals are received (INT, TERM, EXIT, ERR). Critical for cleanup logic: removing temp files, sending alerts on failure, and ensuring safe teardown of resources when a script exits.
trap 'rm -f /tmp/mytemp.*' EXITClean up temp files on any exit · explain & risk-check →trap 'echo "ERROR at line $LINENO"' ERRReport error line number on failure · explain & risk-check →trap 'echo Interrupted; exit 1' INT TERMHandle Ctrl+C gracefully · explain & risk-check →trap '' SIGPIPEIgnore broken pipe signals (common in pipelines) · explain & risk-check →Use `trap 'cleanup' EXIT` instead of duplicating cleanup at every exit point — EXIT fires on all exits (normal, error, signal), so one trap covers all cases.
Reference text is hand-written and may be incomplete — check man trap for your version. Test destructive commands on a non-production system first.