bash - 每次 cmd1 stdout 產生特定字串時執行 cmd2

bash - 每次 cmd1 stdout 產生特定字串時執行 cmd2

我正在嘗試跑步

WID=`xdotool search "Inbox" | head -1`
xdotool windowactivate $WID
xdotool key Up

每次標準輸出

$ CAMEL_DEBUG=all evolution

產生“開始空閒”。

我想出了這個腳本,它可以執行我想要的操作,但只有一次,它並不是每次顯示“啟動空閒”時都執行此操作,而是僅執行一次並停止。我不知道 bash 足夠好以迫使它無休止地重複自己。

exec 3< <(CAMEL_DEBUG=all evolution)

while read line; do
   case "$line" in
   *"starting idle"*)
      echo "'$line' contains staring idle"

    WID=`xdotool search "Inbox" | head -1`
        xdotool windowactivate $WID
        xdotool key Up

      break
      ;;
   *)
      echo "'$line' does not contain starting idle."
      ;;
   esac
done <&3

exec 3<&-

謝謝。

答案1

break命令終止while循環。算了吧。

答案2

你可以嘗試一些更複雜的東西。首先將 的輸出重新導向evolution到檔案:

CAMEL_DEBUG=all evolution > tmpout

然後進行無限while循環來讀取檔案並在找到字串時做出反應:

#!/usr/bin/env bash
while true; do
    while read line; do
    case "$line" in
        *"starting idle"*)
        echo "'$line' contains staring idle"

        WID=`xdotool search "Inbox" | head -1`
        xdotool windowactivate $WID
        xdotool key Up

        break
        ;;
        *)
        echo "'$line' does not contain starting idle."
        ;;
    esac
    done < tmpout
done

相關內容