stdout에 특정 문자열이 포함된 경우 cli 앱을 종료하는 방법은 무엇입니까?

stdout에 특정 문자열이 포함된 경우 cli 앱을 종료하는 방법은 무엇입니까?

많은 정보를 stdout으로 출력하는 명령줄 앱이 있습니다.

stdout에 특정 문자열이 포함되어 있으면 프로그램을 어떻게 종료합니까?

예를 들어 다음과 같습니다.

my_program | terminate_if_contains ERROR

내가 이렇게 하고 싶은 이유는 이 프로그램이 제3자에 의해 작성되었고 stdout에 많은 오류를 출력하지만 첫 번째 오류에서 중지하고 싶기 때문에 프로그램이 끝날 때까지 기다릴 필요가 없기 때문입니다.

답변1

노력하다:

my_program | sed '/ERROR/q'

그러면 다음을 포함하는 첫 번째 줄까지 모든 내용이 인쇄됩니다 ERROR. 그 시점에서 sed종료됩니다. 그 후 곧 my_program대부분의 프로그램을 중지시키는 파이프 파손 신호(SIGPIPE)를 받게 됩니다.

답변2

이 문제에 대한 빠른 해결책은 다음과 같습니다.

사용 예:

$ 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

관련 정보