简体   繁体   English

如何在bash中破坏tail -f命令

[英]How to break a tail -f command in bash

How can I break a tail -f in bash? 如何在bash中打断tail -f Since this question is related to this question 由于这个问题与这个问题有关

tail -f | 尾巴-f | awk and end tail once data is found 一旦发现数据,awk和end tail

I tried the following: 我尝试了以下方法:

#! /bin/bash

tvar="testing"
(set -o pipefail && tail -f <<< "$tvar" | awk '{print; exit} END{ exit 1}'  )

But the script is still hanging on to tail -f 但是脚本仍然挂在tail -f

Well, the problem is not the tail -f but the awk which hangs. 好吧,问题不是tail -f而是挂起的awk It is meant to terminate when EOF is found (with exit 1 ). 这意味着在找到EOF时终止(具有exit 1 )。 But there is no EOF found; 但是没有找到EOF。 the tail -f does not terminate, so there comes no EOF. tail -f不终止,因此没有EOF。

Would the awk terminate, then this would also break the pipe and the tail would receive a SIGPIPE (which would terminate it). 如果awk终止,那么这也将破坏管道,并且tail将收到SIGPIPE(终止)。

You must find a different condition on which to terminate. 您必须找到终止条件。

EDIT: 编辑:

To achieve what you want you can start the tail -f in the background, remember its PID and kill it as soon as you do not need it anymore. 要实现所需的功能,可以在后台启动tail -f ,记住其PID并在不再需要它时立即将其杀死。 Running in the background and using a pipe at the same time is tricky. 在后台运行并同时使用管道非常棘手。 The easiest way to do it would be to use a named pipe (FIFO): 最简单的方法是使用命名管道(FIFO):

mkfifo log.pipe
tail -f log > log.pipe & tail_pid=$!
awk ... < log.pipe
kill $tail_pid
rm log.pipe

It seems that switching from using <<< to echo "$tvar" | tail -f 似乎从使用<<<切换到echo "$tvar" | tail -f echo "$tvar" | tail -f does what you want instead? echo "$tvar" | tail -f是您想要的吗?

$> cat test.sh
#! /bin/bash

tvar="testing"
(set -o pipefail && echo "$tvar" | tail -f | awk '{print} END{ exit 1}'  )
$> ./test.sh
testing
$>

Although the awk doesn't print anything out afterwards. 尽管awk之后没有打印任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM