Search code examples
androidbashgrepadb

grep doesn't terminate after showing requested number of matches


I'm trying to use grep to output the first match and terminate. In my case the stream being searched comes from Android logcat, but this is probably irrelevant:

adb logcat | grep -m1 SomeFilter

I'm limiting the results to a single match using the -m option. If the input stream contains more than one match, the first match is shown and grep terminates as expected. However, if there is only a single match in the input stream, the match is displayed, but grep never terminates. Any idea why?


Solution

  • Have three ideas.

    1) There is no LF symbol nor EOF in the input stream.

    2) grep is actually terminating after seeing the first match. But the adb does not terminate despite grep exits and write to the pipe fails. adb just ignores these write errors and keeps running. You can check if grep has really terminated simply typing pgrep grep in another terminal.

    3) Most likely, if there is really only a single match and nothing more, then probably adb does not write anymore to the pipe, and it never receives write error and SIGPIPE. Thus adb is still running whilst grep has actually terminated.