会话示例:
- 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
Run Code Online (Sandbox Code Playgroud)
如您所见,tail 和 grep 仍在运行。
像下面这样的东西会很棒
#!/bin/bash
tail -f example.log | grep "foobar" &
PID=$!
echo "code goes here"
kill $PID
echo "more code here"
Run Code Online (Sandbox Code Playgroud)
但这只会杀死 grep,而不是 tail。
虽然整个管道都是在后台执行的,但是 .txt 文件grep中只存储了进程的 PID $!。你想告诉kill杀死整个工作。您可以使用%1,这将终止当前 shell 启动的第一个作业。
#!/bin/bash
tail -f example.log | grep "foobar" &
echo "code goes here"
kill %1
echo "more code here"
Run Code Online (Sandbox Code Playgroud)
即使您只是终止该grep进程,该tail进程也应该在下次尝试写入标准输出时退出,因为该文件句柄在grep退出时已关闭。根据 example.log 的更新频率,更新可能几乎立即完成,也可能需要一段时间。