How to terminate a cli app when stdout contains a certain string?

1

I've got a command line app that outputs lots of information to stdout.

How can I terminate the program when stdout contains a certain string?

e.g. something like:

my_program | terminate_if_contains ERROR

The reason I want to do this is because the program is written by a third party, and outputs lots of ERRORS to stdout, but I want to stop on the first error, so I don't have to wait until the program finishes.

Brad Parks

Posted 2016-06-16T19:03:50.037

Reputation: 1 775

Answers

1

Try:

my_program | sed '/ERROR/q'

This prints everything up to and including the first line containing ERROR. At that point, sed quits. Soon after that, my_program will receive a broken pipe signal (SIGPIPE) which causes most programs to stop.

John1024

Posted 2016-06-16T19:03:50.037

Reputation: 13 893

1nice! I didn't know about that /q option... cool! – Brad Parks – 2016-06-16T19:24:50.310

1

Here's my quick solution to this problem:

Examples of usage:

$ watch_and_kill_if.sh ERROR my_program

watch_and_kill_if.sh

#!/usr/bin/env bash

function show_help()
{
  IT=$(CAT <<EOF

  usage: ERROR_STR YOUR_PROGRAM

  e.g. 

  this will watch for the word ERROR coming from your long running program

  ERROR my_long_running_program
EOF
  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$2" ]
then
  show_help
fi

ERR=$1
shift;

$* |
  while IFS= read -r line
  do
    echo $line
    if [[ $line == *"$ERR"* ]]
    then
      exit;
    fi
  done

    if [ "$1" == "help" ]
    then
      show_help
    fi
    if [ -z "$2" ]
    then
      show_help
    fi

    ERR=$1
    shift;

    $* |
      while IFS= read -r line
      do
        echo $line
        if [[ $line == *"$ERR"* ]]
        then
          exit;
        fi
      done

Brad Parks

Posted 2016-06-16T19:03:50.037

Reputation: 1 775