Sunday, April 24, 2016

Bash Ctrl-C Cleanup

Most scripts are pretty simple things, but sometimes one writes a monster and it may create several temporary files, lock files and other detritus while running.  Sometimes you will be nice and delete the junk before the script exits.  

However, if the user would terminate the script forcefully with Ctrl-C or kill, then the garbage will not be removed.

Here is the proper way to handle that in Bash:

 # Trap keyboard interrupt (control-c)
 trap control_c 0 SIGHUP SIGINT SIGQUIT SIGABRT SIGKILL SIGALRM SIGSEGV SIGTERM

 control_c()
 # Control-C Press
 {
   cleanup
   exit $?
 }

 cleanup()
 {
   rm /var/lock/mylockfile
   return $?
 }


La voila!

Herman

No comments:

Post a Comment

On topic comments are welcome. Junk will be deleted.