如何杀死bash中的所有工作?

use*_*013 7 bash job-control

所以,我有一些这样的工作:

sleep 30 | sleep 30 &
Run Code Online (Sandbox Code Playgroud)

自然的思考方式是:

kill `jobs -p`
Run Code Online (Sandbox Code Playgroud)

但这只会杀死第一个sleep而不是第二个。

这样做会杀死两个进程:

kill %1
Run Code Online (Sandbox Code Playgroud)

但是,如果有很多这样的工作在运行,那最多只会杀死一项工作。

它不应该终止具有相同名称但不在此 shell 中运行的进程。

sdu*_*hil 7

xhienne 答案的一个较短版本,但不是纯 bash:

jobs -p | xargs -I{} kill -- -{}
Run Code Online (Sandbox Code Playgroud)

  • `xargs` 不是 bash 的一部分。它是 [`findutils`](https://www.gnu.org/software/findutils/) 的一部分。 (3认同)

xhi*_*nne 6

用这个:

pids=( $(jobs -p) )
[ -n "$pids" ] && kill -- "${pids[@]/#/-}"
Run Code Online (Sandbox Code Playgroud)

jobs -p打印进程组领导的 PID。通过向 提供负 PID kill,我们终止了属于该进程组 ( man 2 kill) 的所有进程。"${pids[@]/#/-}"只是否定存储在 array 中的每个 PID pids