
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!

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:
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
Saturday Morning Comics!
Want another comic like this in your email every Saturday? Sign up here!