trap

noun

say it: “TRAP” /ˈtræp/

A bash command that sets another command to run at a chosen moment, such as when the script ends for any reason.

What does trap do in bash?

trap tells bash to run a command when something happens. With EXIT, it runs when the script ends for any reason: its last line, an exit, a failure, or Ctrl+C. Put the command in single quotes, so $tmp is read at the end, not when the trap is set.

tmp=$(mktemp photos/.moving.XXXXXX)
trap 'rm -f "$tmp"' EXIT
cp inbox/IMG_0413.jpg "$tmp"
sleep 30   # press Ctrl+C now: the scratch file is still removed

In a sentence

  • “Write the trap's command in single quotes so the variable is read at the end.”
  • “A trap on EXIT removed the scratch file even when Sam pressed Ctrl+C.”

Level: Freelancer · More Unix terms at this level

Updated