简体   繁体   中英

How to break a tail -f command in bash

How can I break a tail -f in bash? Since this question is related to this question

tail -f | awk and end tail once data is found

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

Well, the problem is not the tail -f but the awk which hangs. It is meant to terminate when EOF is found (with exit 1 ). But there is no EOF found; the tail -f does not terminate, so there comes no EOF.

Would the awk terminate, then this would also break the pipe and the tail would receive a SIGPIPE (which would terminate it).

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. 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):

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 does what you want instead?

$> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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