Search code examples
bashsignalsbash-trap

In bash, how to catch the "event" that the program exits itself?


I have a bash program that needs to remove a lock file whenever it terminates.

It does not matter if the bash exits at the end of execution or if it failed at some point and exits with an error code, I want to catch this event and do some stuff before it actually terminates for good.

I have read about trap, but if trap is the solution, I do not understand which signal should be given to trap in order to catch all "exits possibilities".

Is trap the solution ? If not, how can this be achieved ?


Solution

  • Try something like

    trap 'cleanup' EXIT
    

    at the start, and have a function cleanup:

    function cleanup()
    {
        # Kill any lingering child processes
        # kill -9 $(jobs -p) 2> /dev/null
        kill -9 0 2> /dev/null
    }