2

I have a shell script running in the background, which runs 5 different jobs.

When I run the shell script all 5 jobs start running in order. When I kill this shell, whichever process is running, will still continue to run, even though I have killed the shell.

$ bash shell.sh & echo $!

this gives me the PID of the shell, which allows me to kill it later if I wish to do so at some point.

#!/bin/bash

JOB1
JOB2
JOB3
JOB4
JOB5

How can I make the shell kill all process running within, once it has been killed?

0
#!/bin/bash
declare -a bgpids

cleanup() {
    for pid in ${bgpids[@]}; do
        kill -9 $pid
    done
}
trap "cleanup" SIGINT SIGTERM

sometask &
bgpids+=("$!")
  • 1
    jobs -p works for pids. But kill -- -0 should be enough. – mikeserv Feb 4 '16 at 20:22
  • I forgot that kill could effectively look up children. Good catch! – DopeGhoti Feb 4 '16 at 20:23
  • It doesnt look up children - but if everybody's in the same process group then just kill the group. kill -0 is a whole different animal to kill -- -0. – mikeserv Feb 4 '16 at 20:25

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.