Bash reading STDOUT stream in real-time

后端 未结 2 826
没有蜡笔的小新
没有蜡笔的小新 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条回答
  • 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
    
    0 讨论(0)
  • 2021-01-14 06:05

    From this unix.stackexchange answer I got following solution:

    cmd_which_streams_new_lines \
    | while read -r line; do
      # process your line here
      echo "${line}"
    
      # when you're done, break the loop (be prepared for messy stderr)
    done
    
    0 讨论(0)
提交回复
热议问题