0

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.

1 Answer 1

2

Within the script itself would require a redirection trick:

#!/bin/bash

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

while read line; do
  echo $line
  sleep 1
done

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 }
  ...
}
1
  • Thanks for the mention of "expect". It's exactly what I needed.
    – Eliot
    Aug 20, 2016 at 12:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .