How to kill all jobs in bash?

So, I have some jobs like this:

sleep 30 | sleep 30 &

The natural way to think would be:

kill `jobs -p`

But that kills only the first sleep but not the second.

Doing this kills both processes:

kill %1

But that only kills at most one job if there are a lot of such jobs running.

It shouldn’t kill processes with the same name but not run in this shell.

Asked By: user23013


You can use pkill and pgrep to kill a list of process names.

From the man page:

pgrep looks through the currently running processes and lists the process IDs which matches the selection criteria to stdout. All the criteria have to match. For example,
pgrep -u root sshd
will only list the processes called sshd AND owned by root. On the other hand,
pgrep -u
will list the processes owned by root OR daemon.
pkill will send the specified signal (by default SIGTERM) to each process instead of listing them on stdout.

An example using pgrep, pkill,

$ pgrep -l

$ pkill $(pgrep

$ cat signal-log
Name: ./ Pid: 12406 Signal Received: SIGTERM
Name: ./ Pid: 12425 Signal Received: SIGTERM
Answered By: Chen A.

Use this:

pids=( $(jobs -p) )
[ -n "$pids" ] && kill -- "${pids[@]/#/-}"

jobs -p prints the PID of process group leaders. By providing a negative PID to kill, we kill all the processes belonging to that process group (man 2 kill). "${pids[@]/#/-}" just negates each PID stored in array pids.

Answered By: xhienne

A somewhat shorter version of xhienne’s answer, but not pure-bash:

jobs -p | xargs -I{} kill -- -{}
Answered By: sduthil

Use kill $( jobs -p )… I love it.
Use this if you’ve jost got too many jobs for kill’s argv (it can happen I guess):

killalljobs() { for pid in $( jobs -p ); do kill -9 $pid ; done ; }

Answered By: user2497

This will kill all jobs, most recently created first:

while kill %%; do :; done

This stops when there are no more jobs to kill, and prints:

bash: kill: %%: no such job

Works in zsh too.

Answered By: Tom Hale
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.