Bash
使用 BASH 腳本從第三個來源讀取控制台中顯示的輸出?
我在理解如何
read
從控制台而不是使用者輸入“讀取”資訊時遇到問題。有效地“getline”?從控制台。這是我的場景。我將發送一個
echo "information" | ncat "IP" "PORT"
到位於網路內部的一個埠,該埠執行一個守護程序來擷取正確的資訊。如果我發送的資訊不正確,我將收到一條預定義的消息,告訴我發送的資訊不正確並重試。但是,如果資訊是正確的,我會得到一個不同的響應,我不知道響應是什麼。
這是迄今為止我嘗試過的 BASH 腳本的片段。
if [[read -r line ; echo "$line" ; while "$line" == "Information wrong try again!"]] ; continue elif [[read -r line ; echo "$line" ; while "$line" != "Information wrong try again!"]] ;break
我對 bash 很陌生,所以我對語法的使用可能不正確。
恐怕你的語法都是錯誤的。我想你正在尋找這樣的東西:
if [ "$line" = "Information wrong try again!" ]; then echo "Try again" else echo "All's well" fi
當然,細節將取決於您如何執行腳本。如果你希望它是一個無限循環並重新執行
echo "information" | ncat "IP" "PORT"
命令直到它工作,你想要這樣的東西:line=$(echo "information" | ncat "IP" "PORT") while [ "$line" = "Information wrong try again!" ]; do line=$(echo "information" | ncat "IP" "PORT") sleep 1 ## wait one second between launches to avoid spamming the CPU done ## At this point, we have gotten a value of `$line` that is not `Information wrong try again!`, so we can continue. echo "Worked!"
或者,類似地:
while [ $(echo "information" | ncat "IP" "PORT") = "Information wrong try again!" ]; do sleep 1 ## wait one second between launches to avoid spamming the CPU done ## rest of the script goes here echo "Worked!"