Linux: Block until a string is matched in a file (“tail + grep with blocking”)

后端 未结 7 1700
小蘑菇
小蘑菇 2020-12-05 11:58

Is there some one-line way in bash/GNU tools to block until there\'s a string matched in a file? Ideally, with timeout. I want to avoid multi-line loop.

Upda

7条回答
  •  长情又很酷
    2020-12-05 12:36

    $ tail -f path | sed /pattern/q
    

    or, if you want to suppress the output of non-matching lines:

    $ tail -f path | sed -n '/pattern/{p; q;}'
    

    A simple-minded way to add a timeout is to do:

    $ cmd& sleep 10; kill $! 2> /dev/null
    

    (Suppress the errors from the kill so that if the process terminates before the time expires, you don't get the "No such process" warning). Note that this is not at all robust, since it is possible that cmd will terminate and the pid count will wrap around and some other command will have that pid by the time the timer expires.

提交回复
热议问题