Bash reading STDOUT stream in real-time

后端 未结 2 841
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 05:43

I have searched for this and expected to find hundreds of solutions yet found none !

I would like to read the STDOUT stream and wait for a specific string to appear,

2条回答
  •  旧时难觅i
    2021-01-14 05:53

    You can pipe into grep to do the matching and have it exit when it encounters a match. That will also exit the program producing the output.

    if mycommand | grep something -q; then
        dosomething
    fi
    

    The above will quit if anything matches (-q), but not display the result. If you want to see the output, you can quit on the first match (using -m1):

    RESP=$(mycommand | grep something -m1)
    

    Read the man-pages for grep for more information.


    If you don't want to cancel the program producing the output, you could try writing it to file in the background, then tail that file:

    mycommand > output &
    if tail -f output | grep something -q; then
        dosomething
    fi
    

提交回复
热议问题