2

我正在编写一个障碍来阻止脚本的执行,直到记录了某个关键字。脚本非常简单:

tail -F -n0 logfile.log | while read LINE; do
    [[ "$LINE" == *'STOP'* ]] && echo ${LINE} && break;
done

或者

tail -F -n0 logfile.log | grep -m1 STOP

问题是它不会在检测到关键字后立即退出,而只会在写入下一行之后退出。IE:

printf "foo\n"  >> logfile.log  # keeps reading
printf "foo\n"  >> logfile.log  # keeps reading
printf "STOP\n" >> logfile.log  # STOP printed
printf "foo\n"  >> logfile.log  # code exits at last

不幸的是,我不能依赖在“STOP”之后将记录另一行的事实(至少不在对我的目的有用的间隔内)。

到目前为止找到的解决方法是tail另一个我知道肯定会经常更新的文件,但是什么是“干净”的解决方案,以便代码在记录STOP后立即退出?

4

1 回答 1

4

中,执行形式的命令时

command1 | command2

并且command2死亡或终止,接收/dev/stdout来自的管道command1 被破坏。然而,这不会command1立即终止。

所以要实现你想要的是使用进程替换而不是管道

awk '/STOP/{exit}1' < <(tail -f logfile)

当您使用时,您可以更详细地查看行为:

$ touch logfile
$ tail -f logfile | awk '/STOP/{exit}1;END{print "end"}'

awk程序将检查是否看到“STOP”,如果没有再次打印该行。如果看到“STOP”,它将打印“end”

当你在另一个终端做

$ echo "a" >> logfile
$ echo "STOP >> logfile
$ echo "b" >> logfile

您会看到打印以下输出:

a             # result of print
end           # awk test STOP, exits and executes END statement

此外,如果您仔细观察,您会发现此时已经终止。

ps在发送“停止”之前:

13625 pts/39   SN     0:00  |        \_ bash
32151 pts/39   SN+    0:00  |            \_ tail -f foo
32152 pts/39   SN+    0:00  |            \_ awk 1;/STOP/{exit}1;END{print "end"}

ps发送“STOP”后:

13625 pts/39   SN     0:00  |        \_ bash
32151 pts/39   SN+    0:00  |            \_ tail -f foo

所以 awk 程序终止了,但tail没有崩溃,因为它还没有意识到管道已损坏,因为它没有尝试写入它。

当您在终端中使用管道执行以下操作时,您会看到退出状态tail

$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
$ 141 0

哪个状态awk很好地tail终止了,但以退出代码 141 终止,这意味着SIGPIPE.

于 2018-10-15T09:32:39.607 回答