I have a command that needs to run in the background for the duration of the script. Meaning until the rest of the script has successfully ran or met Ctrl+c or been otherwise prematurely terminated.

The problem is, if I use command &, it keeps running even after the script has terminated, until the terminal that started it has been terminated.

Is there a way to bind the background command to the foreground script?

  • Put a wait at the end of the script. – S.S. Anne Feb 21 at 12:47
  • this doesn't work, remember, I want a bg command to terminate, once its parent process has terminated – user2741831 Feb 21 at 13:05

This answer:

To just kill all background jobs managed by bash, do

kill $(jobs -p)

A basic approach is to put this line at the end of the main script, the script may never get to it though. More advanced approach is to create a trap in the main script:

trap 'kill $(jobs -p) 2>/dev/null' EXIT

Define the trap before you start the background job. The kill command will be run even if the main script is terminated prematurely (unless it's terminated forcefully, e.g. with SIGKILL).

But remember your job may ignore SIGTERM it gets from the kill in the trap.

If you want to kill a specific background job only (as opposed to all background jobs), store its PID in a variable and use the variable in the trap:

trap 'kill "$jpid" 2>/dev/null' EXIT


your_job &


I think there's a flaw though: if the main shell is terminated between your_job & and jpid="$!" then the trap will have no $jpid to work with. There is no such flaw in kill $(jobs -p).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.