In bash
and zsh
I would use something like this (after considering the comment from pizdelect about the process group):
jobs -p | extract_pids | xargs --no-run-if-empty kill -TERM -- || true
where
extract_pids() {
awk '{
if (NF == 1) { print -$1 }
else if (NF > 1) {
if ($2 == "+" || $2 == "-") { print -$3 }
else { print -$2 }
}
}'
}
As far as I tested jobs -p
returns the PID
s in bash
, f.i.:
$ jobs -p
41659
but can have these formats in zsh
, f.i.:
$ jobs -p
[1] 206 running sleep 10
[2] - 208 running sleep 10
[3] + 210 running sleep 10
extract_pids
tries to handle these (4) cases.
Note: checking the processes with jobs -p
can return PID
s, which are already gone at the time xargs kill
is invoked, so we ignore errors with a trailing || true
.
kill $(jobs -p)
seems easier. – jw013 Jul 19 '12 at 22:00for pid in $(jobs -p); do kill $pid; done
? – jw013 Jul 19 '12 at 22:27jobs
which only works if the jobs happen to be numbered consecutively. Oh, and “kill jobs individually” is meaningless: passing multiple PIDs to thekill
command does exactly the same thing as passing them separately. – Gilles 'SO- stop being evil' Jul 19 '12 at 23:52