2

示例会话:

- cat myscript.sh 
#!/bin/bash
tail -f example.log | grep "foobar" &
echo "code goes here"
# here is were I want tail and grep to die
echo "more code here"

- ./myscript.sh

- ps
  PID TTY          TIME CMD
15707 pts/8    00:00:00 bash
20700 pts/8    00:00:00 tail
20701 pts/8    00:00:00 grep
21307 pts/8    00:00:00 ps

如您所见,tail 和 grep 仍在运行。


像下面这样的东西会很棒

#!/bin/bash
tail -f example.log | grep "foobar" &
PID=$!
echo "code goes here"
kill $PID
echo "more code here"

但这只会杀死grep,而不是tail。

4

2 回答 2

4

虽然整个流水线都是在后台执行的,但只有grep进程的 PID 存储在$!. 你想告诉kill杀死整个工作。您可以使用%1,这将终止当前 shell 启动的第一个作业。

#!/bin/bash
tail -f example.log | grep "foobar" &
echo "code goes here"
kill %1
echo "more code here"

即使您只是终止该grep进程,该tail进程也应在下次尝试写入标准输出时退出,因为该文件句柄在grep退出时已关闭。根据 example.log 的更新频率,可能几乎是立即更新,也可能需要一段时间。

于 2013-11-11T13:05:46.547 回答
2

您可以kill %1在脚本末尾添加。

这将杀死first创建的背景,这样就不需要找出 pids 等。

于 2013-11-11T13:11:16.370 回答