當 stdout 包含某個字串時如何終止 cli 應用程式?

當 stdout 包含某個字串時如何終止 cli 應用程式?

我有一個命令列應用程序,可以向標準輸出輸出大量資訊。

當 stdout 包含某個字串時如何終止程式?

例如:

my_program | terminate_if_contains ERROR

我想這樣做的原因是因為該程式是由第三方編寫的,並向標準輸出輸出大量錯誤,但我想在第一個錯誤時停止,所以我不必等到程式完成。

答案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

相關內容