Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate a program immediately after grep found a specific string in stdout in shell

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.

like image 483
Schnarco Avatar asked Oct 16 '25 02:10

Schnarco


1 Answers

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.

like image 61
user1934428 Avatar answered Oct 17 '25 17:10

user1934428



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!