Suppose I have an executable which connects to an external machine and outputs a bunch of stuff to stdout over many minutes. At the end of that output there'll be a keyword such as "STOP", or the EOF character or something. After that keyword/EOF is printed the executable will sit there still executing but not sending any more output. It will not terminate by itself.

Now I want to pipe the output of this executable to a bash script that does this:

  1. Read what's being piped in and write it all to stdout.
  2. When you see the word "STOP" (or perhaps the character EOF), kill the executable.

I can use pkill to kill the executable. I could maybe use some combination of tee and grep, but I don't see how to do something once I get a match on the grep.


Within the script itself would require a redirection trick:


exec 1> >(tee >(awk '/STOP/{system("kill '"$$"'")}'))

while read line; do
  echo $line
  sleep 1

And thence:

bash-4.1$ (echo can; echo t; echo STOP; echo believing) | bash datscript

Another option might be expect, e.g. something like

#!/usr/bin/env expect
spawn thatconnectingexecutablething
set timeout 7
expect {
  -ex "STOP" { exit 1 }
  eof { exit 1 }
  timeout { exit 1 }
|improve this answer|||||
  • Thanks for the mention of "expect". It's exactly what I needed. – Eliot Aug 20 '16 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.