trap

Execute commands when the shell receives signals or exits.

low risk

interactive breakdown — edit the command and press Explain
$ 
⚠ Risks & cautions
What it does

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.

Examples
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 →
Pro tip

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.

Related
set jobs logger
Open the full explainer →More in Shell & Scripting

Reference text is hand-written and may be incomplete — check man trap for your version. Test destructive commands on a non-production system first.