Grep from stream until finding match

97 Views Asked by At

I have a command that outputs a stream say adb logcat. I want to pipe that to grep until I find the first match of a certain query. At this point I want to stop the first command:

I've tried:

MY_VARIABLE=$(adb logcat | grep -m 1 'my variable (.*)')

But the problem is that the process will not stop even if grep finds the first match.

My guess is that I need to run adb logcat in nohup, pipe that command to grep, then stop it when done. But I'm not sure how to do this.

1

There are 1 best solutions below

4
On

You need to unbuffer the input to grep, that is unbuffer adb logcat. A similar example shows another command (a Perl one-liner that prints numbers 1-13, one after another, pausing 1 second in between numbers). Unbuffering the Perl command with $| = 1; does the trick and causes grep to return after 3 seconds instead of after the Perl command exits, which is after 13 seconds:

$ time ( perl -le 'BEGIN { $| = 1; } for ( 1..13 ) { print; sleep 1; }' | grep -m 1 '3' )
3
( perl -le 'BEGIN { $| = 1; } for ( 1..13 ) { print; sleep 1; }' | grep -m 1 )  0.01s user 0.01s system 0% cpu 3.047 total

$ time ( perl -le 'for ( 1..13 ) { print; sleep 1; }' | grep -m 1 '3' ) 
3
( perl -le 'for ( 1..13 ) { print; sleep 1; }' | grep -m 1 '3'; )  0.01s user 0.02s system 0% cpu 13.080 total