DEV Community

Discussion on: Use `trap` to catch signals - Linux Tips

Collapse
 
mccurcio profile image
Matt Curcio • Edited

Bo, nice tutorial, however I don't really know the context for using this script. Could you shine a little more light on why? When? And what for?
Thanks

Collapse
 
bitecode profile image
BC

Hey Matt, this could be useful when you do some shell programming. For example, if your shell script will create some temporary files in order to get the task done, and once the task is done, you will clean those temporary files, the logic is something like this (psudo-code):

prepare_temporary_files()
do_task() # may take a long time
clean_temporary_files()

Now when your shell is running do_task part, you press Ctrl+C, your script is interrupted and stopped, but those temporary files never get cleaned up.

To fix this, you can add trap clean_temporary_files 2 to your script, which will caught the Ctrl+C signal (#2 SIGINT), then it will do the clean_temporary_files function.

Collapse
 
mccurcio profile image
Matt Curcio

Very interesting,
Thanks