Skip to Content
A stick figure smiling

Here's a preview from my zine, Bite Size Bash! If you want to see more comics like this, sign up for my saturday comics newsletter or browse more comics!

Image of a comic. To read the full HTML alt text, click "read the transcript".
read the transcript!

when your script exits, sometimes you need to clean up

nonplussed stick figure with short curly hair: oops, the script I created a bunch of temp files I want to delete

trap sets up callbacks

trap COMMAND EVENT

COMMAND: what command to run
EVENT: when to run the command

bash runs COMMAND when EVENT happens

trap "echo 'hi!!!'" INT

OS, represented by a box with a smiley face: <sends SIGINT signal>
bash, also represented by a box with a smiley face: ok, time to print out hi!!!!

events you can trap

  • unix signals (INT, TERM, etc)
  • the script exiting (EXIT)
  • every line of code (DEBUG)
  • function returns (RETURN)

example: kill all background processes when Ctrl+C is pressed

trap "kill $(jobs -p)" INT

when you press CTRL+C, the OS sends the script a SIGINT signal

example: cleanup files when the script exits

function cleanup() {
   rm -rf $TEMPDIR
   rm $TEMPFILE
}
trap cleanup EXIT

EXIT is a fake “signal” that triggers on exit