Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically cancel binary execution when certain output is detected

Is it possible to somehow run an executable through the shell and automatically make it stop executing the moment a specific string is matched/detected in the output? Just as if i would hit CTRL+C, manually?

If yes, how?

like image 607
SquareCat Avatar asked Feb 18 '26 06:02

SquareCat


2 Answers

use a coprocess:

coproc CO { yourcommand; }
while read -ru ${CO[0]} line
do
    case "$line" in
        *somestring*) kill $CO_PID; break ;;
    esac
done

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.

like image 84
Barmar Avatar answered Feb 20 '26 20:02

Barmar


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'
1
2
3
4
5
6
7
8
9

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=1
while : ; do
  echo $n
  n=$((n+1))
  sleep 1
done

This script foo.sh was executed by saying:

$ time bash foo.sh | awk '/9/{print;exit}1'
1
2
3
4
5
6
7
8
9

real    0m9.097s
user    0m0.011s
sys     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'
like image 30
devnull Avatar answered Feb 20 '26 20:02

devnull



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!