bash - how to automatically send SIGINT on matching line in stdout

Viewed 77

Given: A foo_command that runs as the last line of a script I control. I don't control foo_command.

I'm looking for something like:

foo_command | interrupt_if_grep "warning"

foo_command prints progress and sometimes warnings to stdout. I'd like to have interrupt_if_grep passthrough stdout, but send SIGINT to foo_command if it encounters a matching warning line, i.e. what I would do manually.

To summarize all the cases, foo_command can:

  1. succeed - I want to passthrough stdout as normal
  2. warning to stdout, then succeed - I want to detect warning and SIGINT (returning error)
  3. error - I want script to error as normal

Some things I tried that don't work for me:

# foo_command doesn't handle SIGPIPE properly and this suppresses normal stdout output
foo_command | grep -m1 "warning" && exit 1

# error code of `foo_command` is "lost"
foo_command | tee foo_stdout.txt
! grep "warning" foo_stdout.txt  # error if "warning" is found
1 Answers

The second solution you tried would work with the pipefail option enabled, I think:

set -o pipefail
foo_command | tee foo_stdout.txt || exit 1
! grep "warning" foo_stdout.txt
Related