3

I'm running a program which executes (mostly) correctly, but then hangs. I'd like to run the program such that once it outputs a certain string, or stops producing output it gets killed.

The output string I'm interested in is:

Was exported to:

After I see this output, I'd like to automatically kill the program. Alternatively, the program stops producing output after this, so I could kill it based on that condition. How can I accomplish one of these?

1

2 Answers 2

3

You could do:

sh -c 'echo "$$"; exec stdbuf -oL "$0" "$@"' my-program with its args | (
  IFS= read -r pid &&
    sed '/Was exported to:/q' &&
    kill -s PIPE "$pid"
)

Where we run my-program in the same process as the one that earlier ran sh (and sent its pid to the pipe), under stdbuf -oL (as found on GNU or FreeBSD based systems) so as to restore line based buffering (applications tend to do block based buffering when their output doesn't go to a terminal).

At the other end of the pipe, sed waits for the first occurrence of Was exported to: and quits. After which a SIGPIPE signal is sent to the pid which should cause the process to terminate. Without that kill, my-program would only receive the SIGPIPE if it wrote something to the pipe after grep has terminated.

2

One option is to run this tool as a Process substitution to grep.

grep -m 1 "Was exported to:" <(<command>)

The -m 1 tells grep to stop running after the first match, and once it stops running, the command inside the <( ... ) will also be killed. But it's a bit of an "ugly" hack, in my opinion.

Still using grep, but not having to run the command inside, is to redirect the output to a file, and run it in the background, and then read the file with tail -F, grep the output, and kill the process after the first match.

COMMAND > $OUTPUTFILE & tail --pid=$! -n +1 -F $OUTPTFILE | (grep -q -m 1 "Was exported to:" && kill $!)

The --pid=$! is to ensure that tail also stops running once the process finishes or killed.

But both will only work if the line you're greping is followed by a newline.

1
  • very cool, thanks Commented Jun 20, 2022 at 4:45

You must log in to answer this question.

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