Automatically cancel binary execution when certain output is detected
use a coprocess:
coproc CO { yourcommand; }while read -ru ${CO[0]} linedo case "$line" in *somestring*) kill $CO_PID; break ;; esacdone
Note that if the command buffers its output, as many commands do when writing to a pipe, there will be some delay before the string is detected.
You could use awk
:
program | awk '/pattern/{exit}1'
If you also want to print the line containing the pattern, say:
program | awk '/pattern/{print;exit}1'
For example:
$ seq 200 | awk '/9/{print;exit}1'123456789
EDIT: (With reference to your comment, whether the program would stop or not.) Following is a script that would execute in an infinite loop:
n=1while : ; do echo $n n=$((n+1)) sleep 1done
This script foo.sh
was executed by saying:
$ time bash foo.sh | awk '/9/{print;exit}1'123456789real 0m9.097suser 0m0.011ssys 0m0.011s
As you can see, the script terminated when the pattern was detected in the output.
EDIT: It seems that your program buffers the output. You could use stdbuf
:
stdbuf -o0 yourprogram | awk '/pattern/{print;exit}1'
If you're using mawk
, then say:
stdbuf -o0 yourprogram | mawk -W interactive '/pattern/{print;exit}1'