views:

58

answers:

1

Suppose we have a BASH script running some commands in the background. At some time we want to kill all of them, whether they have finished their job or not.

Here's an example:

function command_doing_nothing () {
  sleep 10
  echo "I'm done"
}

for (( i = 0; i < 3; i++ )); do
  command_doing_nothing &
done

echo "Jobs:"
jobs

sleep 1

# Now we want to kill them

How to kill those 3 jobs running in the background?

+2  A: 

To kill ALL jobs (as long as this script is running in its own shell instance):

for x in $(jobs -p); do kill $x; done
Andy
It's works! thanks!
Arko
Feel free to accept it :)
Andy
Done, was confused between vote up and accept ;-)
Arko
Please don't do `kill -9` when it's unnecessary. http://speculation.org/garrick/kill-9.html
Dennis Williamson
@Dennis good point, amended
Andy