Just keep in mind that the selected answer is bashism , which means a solution like
trap "{ rm -f $LOCKFILE }" EXIT
will only work in bash (it will not catch Ctrl + c if the shell is dash or classic sh ), but if you need compatibility, you still need to list all the signals you want to capture.
Also keep in mind that when a script exits the trap for the signal "0" (aka EXIT), it always executes, which leads to a double execution of the trap command.
In order not to set all signals in one line, if there is an EXIT signal.
To better understand this, see the following script, which will work on different systems without changes:
#!/bin/sh on_exit() { echo 'Cleaning up...(remove tmp files, etc)' } on_preExit() { echo echo 'Exiting...'
This solution will give you more control, since you can run some of your code when the actual signal appears just before the final exit ( preExit function), and if necessary, you can run some code with the actual EXIT signal (final stage of exit)
Alex Jan 9 '17 at 19:57 2017-01-09 19:57
source share