kill all background jobs managed by
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
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).