2016-08-22 112 views
-1

我遇到了一個問題,我的bash腳本打破了一個嵌套的while循環從尾部的日誌文件中讀取一行。嵌套while循環子進程

我需要什麼:嵌套的while循環讀取日誌文件應該找到一些正則表達式。如果這是真的把它保存到一個變量並打破循環。在循環外部還有一個while循環,用於檢查是否應該將一些數據發送到Confluence頁面。如果不是時間,則在while循環中找到一條與正則表達式相同的行。

我做了一個MVCE:

#!/bin/bash  

counterSearch=0  

tail -n0 -f $logfile | { 
    while true; do 
     currentMinute=$(date +%S)  

     # Checks if $currentSecond is set to 59. If true do something. 
     # Else go back to while loop. 
     if [[ $currentSecond -eq 59 ]]; then 
      echo "Hello. This is 59 seconds outside while read line loop" 
     fi 

     # This while loop should always check if in the $logfile a specific line if found. 
     # If true save it and go back to the outside while loop. When a new line is found 
     # execute it again. 
     while read line ; do 
      if echo "$line" | grep -e "/rest/api/2/search.*PASSED" 1>/dev/null 2>&1 ; then 
       echo "$date - Search and passed API action" >> $log 
       counterSearch=$((counterSearch+1)) 
      fi 
     done 
    done 
}  

的問題是,在保持運行的內部while循環。如果沒有突破到外部while循環。我已經用函數和帶有一個調用一個或另一個循環的if/else的函數嘗試過它。

+1

相關? [在while循環中修改變量不記住](http://stackoverflow.com/q/16854280/1983854) – fedorqui

+0

我不這麼認爲。他不必逃避while循環。我只需要在while循環中找到一行,否則什麼都沒有。 –

+1

那麼,你的代碼有什麼問題?它是否因錯誤而失敗?它不像你期望的那樣運行嗎?不要只是粘貼你的代碼,並期望我們找出問題和解決方案。 – larsks

回答

-1

while循環在子shell

執行試試這個代碼:

#!/bin/bash  

export counterSearch=0  

tail -n0 -f $logfile | { 
    while true; do 
     currentMinute=$(date +%M) 
     currentSecond=$(date +%S) 

     # Checks if $currentSecond is set to 59. If true do something. 
     # Else go back to while loop. 
     if [[ $currentSecond -eq 59 ]]; then 
      echo "Hello. This is 59 seconds outside while read line loop" 
     fi 

     # This while loop should always check if in the $logfile a specific line if found. 
     # If true save it and go back to the outside while loop. When a new line is found 
     # execute it again. 
     while read line ; do 
      if echo "$line" | grep -e "/rest/api/2/search.*PASSED" 1>/dev/null 2>&1 ; then 
       echo "$date - Search and passed API action" >> $log 
       export counterSearch=$((counterSearch+1)) 
      fi 
     done 
    done 
} 
+0

不幸沒有成功。第一條if語句沒有執行。 –

+0

我編輯了代碼。你可以再試一次,請 –

+0

你可能已經改變了在if語句中的右邊那個變量?我看到它已經哈哈!不管怎樣,謝謝。 –