在检测到琴弦时退出尾巴 [英] Exit tail upon string detection

查看:81
本文介绍了在检测到琴弦时退出尾巴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a barrier to stall the execution of a script until a certain keyword is logged. The script is pretty simple:

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

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

问题是它不会在检测到关键字后立即退出,而仅在下一行写完之后 .即:

The thing is it doesn't quit as soon as the keyword is detected, but only after the next line is written. I.e:

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"命令之后将记录另一行. (至少不在对我有用的时间间隔内).

Unfortunately I can't rely on the fact that another line will be logged after the "STOP" (not within an interval useful for my purposes at least).

到目前为止找到的解决方法是tail我肯定也知道另一个文件经常被更新,但是什么是干净的"文件呢?解决方案,以便代码在记录 STOP ?

The workaround found so far is to tail also another file I know for sure gets updated quite frequently, but what is the "clean" solution so that the code will exit right after it logs STOP?

推荐答案

的问题时,您会看到行为的细节:


When you use awk, you can see the behaviour in a bit more detail:

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

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

This awk program will check if "STOP" is seen, and if not print the line again. If "STOP" is seen it will print "end"

当您在另一个终端中做

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

您看到打印以下输出:

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

此外,如果您仔细观察的话,还会看到至此已经终止.

Furthermore, if you look more closely, you see that awk is at this point already terminated.

ps,然后发送"STOP":

ps before sending "STOP":

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"后:

ps after sending "STOP":

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

因此awk程序终止了,但是tail并未崩溃,因为它尚未意识到管道已断开,因为它没有尝试写入该管道.

So the awk program terminated, but tail did not crash because it is not yet aware the pipe is broken as it did not attempt to write to it.

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

When you do the following in the terminal with the pipeline, you see the exit status of tail:

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

其中指出awk终止良好,但tail终止,退出代码为141,表示SIGPIPE.

Which states that awk terminated nicely, but tail terminated with exit code 141 which means SIGPIPE.

这篇关于在检测到琴弦时退出尾巴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆