2

I have a follow-up question on Checking if output of a command contains a certain string in a shell script. However, the answers given in this post do not suit my problem. For expample,

./somecommand | grep -q 'string' && echo 'matched'

throws "matched" once somecommand has finished and grep found "string" in its stdout. In my case, I would like to terminate somecommand immediately after "string" has been piped to the grep command. So far, I have

./somecommand | sed '/string/q',

but I am wondering whether there exists a better solution than waiting for a broken pipe signal.

Schnarco
  • 183
  • 4
  • 3
    Just omit `&& echo 'matched'` if you don't want that part. There is no way to avoid a broken pipe signal if you break the pipe and the writer continues to write to the pipe enough to trigger the signal. The reading side isn't waiting; it quits as soon as the string is found. – tripleee Dec 15 '20 at 11:58

1 Answers1

0

It depends on what somecommand is doing. Let's assume that it continuously produces something on stdout. In this case, you can't do much better than closing the pipe, which will kill the command, but even this does not mean that somecommand terminates as soon as it produces the offending string, but only as soon as grep receives the line with the string. Buffering gets into play.

If, however, somecommand is producing something on stdout only once in a while, closing the pipe would kill it only during the next output, and it can be silent in between. In this case, the receiving part (grep in your case, but it could also be a specifically tailored program from your side) would need to know the PID of the sender (somecommand), so that it could kill it.

If this is a necessity, you could write script which uses for instance ps or pstree, which searches for a process executing somecommand and has the same parent PID as the killing process, to find out which process to kill; after all, there could be several instances of somecommand be executing, and you don't want to kill the wrong one.

user1934428
  • 19,864
  • 7
  • 42
  • 87