Bash 杀死后台命令块

Bash kill background commands block

我有一些 bash 脚本,我在其中放置了一个命令块,然后想要终止它们

#!/bin/bash
{ sleep 117s; echo "test"; } &
ppid=$!
# do something important
<kill the subprocess somehow>

我需要找到一种方法来终止子进程,这样如果它仍在休眠,那么它就会停止休眠并且不会打印 "test"。我需要在脚本中自动完成,所以我不能使用另一个 shell.

到目前为止我已经尝试过的:

  1. kill $ppid - 根本不会终止睡眠(也有 -9 标志),睡眠 ppid 变为 1 但不会打印测试
  2. kill %1 - 结果与上面相同
  3. kill -- -$ppid - 它抱怨 kill: (-30847) - No such process(子进程仍然在这里)
  4. pkill -P $ppid - 测试已打印

我该怎么做?

只需更改您的代码即可:

{ sleep 117s && echo "test"; } &

来自 bash man:

command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero.

演示:

$ { sleep 117s; echo "test"; } &
[1] 48013
$ pkill -P $!
-bash: line 102: 48014 Terminated              sleep 117s
$ test

[1]+  Done                    { sleep 117s; echo "test"; }



$ { sleep 117s && echo "test"; } &                                                                                                      
[1] 50763
$ pkill -P $!                                                                                                      
-bash: line 106: 50764 Terminated              sleep 117s

运行命令组在它自己的子shell。使用 set -m to 运行 sub-shell 在它自己的进程组中。杀死进程组

#!/bin/bash
set -m
( sleep 117s; echo "test"; ) &
ppid=$!
# do something important
kill -- -$ppid