How to raise and take care of shell scripts: Cleanup
Cleanup at script's end
Every program should do a little cleanup work before the final exit, that means: delete temporary created files, kill still running background children and so on. But a program can also be terminated from outside by sending a signal to it (the command to do such nasty things has the appropriate name kill). In this case there are two possibilities which can help you: A little programmer's discipline and trap:
- discipline: Create temporary files in a place, where you can find them later (for instance: create an own directory for them) or store their pathnames. Use the bash job control (right: man bash shows how to use it) to control your background jobs. When writing a large bash script I often use a cleanup function to do the washing-up. This function will also exit the script with an appropriate exit code, given as a functional parameter. I use this function also in situations, when a fatal error occurs.
- trap: The name is program - it's a trap, which waits for signals and then snaps. It's a way
to cleanly exit a script in order to react to an incoming signal (for details see: right again -
man 7 signal). You can define a specific action (for instance to call the cleanup function),
you can ignore the signal (in most cases not a good idea) and something else.
trap "cleanup 1" 1 2 3 15 make sure that your script calls the named function when receiving a "please terminate" signal.
There's no way to trap two signals: SIGSTOP and SIGKILL will always immediately terminate the process, if the caller has the permission to do that (is "root" or the process owner).

