Q:

Kill running background jobs inside a shell script

I have created a shell script that runs multiple processes in the background, and at the end listens for the user's keyboard, when enter is pressed, it kills the previously created processes.
Something like :
#!/bin/sh
process_1 &
process_2 &
process_3 &

read -p "PRESS [ENTER] TO TERMINATE PROCESSES." PRESSKEY

kill -2 `jobs -p`

Notice that I run the processes in the background (the later &), I thought that when I do something like :
kill -2 `jobs -p`

All the jobs running in the background would be killed, but it actually tells me that my command is invalid, so I assume that jobs -p doesn't return anything.
Any idea on how to kill process_1 process_2 and process_3 ?? Thanks in advance.

A:

You can store the PIDs in a space separated list and kill that:
process_1 & pids="${pids-} $!"
process_2 & pids="${pids-} $!"
process_3 & pids="${pids-} $!"

read -p "PRESS [ENTER] TO TERMINATE PROCESSES." PRESSKEY

kill -2 $pids # Without quotes to make the PIDs separate arguments

(The ${pids-} syntax is to avoid errors when using set -o nounset.)

