Assuming your Java code just exits on its own when it receives SIGPIPE
, you can just pipe the output to grep
and have grep exit as soon as it sees a match. Assuming you are using a version of
grepthat supports the
-moption (GNU and BSD
grepboth do), you can have
grep` exit after the first match:
java ... | grep -m 1 'Results:'
One slight catch: because of buffering, your java
program may continue to run for an abitrarily long time before grep
actually sees the "Results" line.
Using only standard grep
, you can use tee
to both display the output and exit after finding any match.
java ... | grep 'Results:' | tee | grep -q '.*'
This suffers the same buffering issue, but amplified: not only may the first grep
have to wait before it actually receives the "Results" line, but tee
may similarly need to wait before it finally gets the same line. Further, if the line is too small, the first grep
may never produce any more output, requiring you to wait for java
to exit naturally before tee
ever sees any input.