shell

How do I kill background processes / jobs when my shell script exits?


I am looking for a way to clean up the mess when my top-level script exits.

Especially if I want to use set -e, I wish the background process would die when the script exits.


Solution

  • To clean up some mess, trap can be used. It can provide a list of stuff executed when a specific signal arrives:

    trap "echo hello" SIGINT
    

    but can also be used to execute something if the shell exits:

    trap "killall background" EXIT
    

    It's a builtin, so help trap will give you information (works with bash). If you only want to kill background jobs, you can do

    trap 'kill $(jobs -p)' EXIT
    

    Watch out to use single ', to prevent the shell from substituting the $() immediately.