2017-06-19 156 views
1

我有下面的代碼,它不會發送grep輸出到電子郵件,但它顯示輸出命令行。不知道我做錯了運行bash命令後沒有收到grep輸出的郵件

sudo tail -f  /path/to/file | while read line ; do  
    egrep 'successfully started \[[0-9] out of [0-9]\] components|successfully started \[[0-9] out of [0-9]\] components'  
    if [ $? -eq 0 ]; then 
     (echo " RESTARTS"; echo; echo $line) | mail -s "RESTART" [email protected] 
    else 
     echo " FAILS" 
    fi 
done 

[更新]

還有一種辦法,我想這樣做,但它不會發送email..I只是確保我能擺脫循環,不會永遠持續下去,因此這就是爲什麼我把尾巴而

while read line; do 

    echo "$line" | sudo tail -f /opt/bmc/ao/cdp/tomcat/logs/grid.log 

    if [ $(echo "$line" | grep -E 'successfully started \[[0-9] out of [0-9]\] components|successfully started \[[0-9] out of [0-9]\] components' | wc -l) -ne 0 ]; then 
     (echo "CDP RESTARTS"; echo; echo "$line") | mail -s "BAOCDP AUTO RESTART" [email protected] 

     break 
    fi 

done 
+0

取出(腳本 –

+0

OK,我會嘗試的 –

+0

@RamanSailopal這將無法正常工作,只有'echo $ line'會被傳送到'mail',而前兩個回聲會進入stdout – Aaron

回答

0

,你希望它在$line變量的內容合作grep無法猜測,你必須把它提供給下面的命令:

egrep 'successfully started \[[0-9] out of [0-9]\] components|successfully started \[[0-9] out of [0-9]\] components' <<< "$line" 

echo "$line" | egrep 'successfully started \[[0-9] out of [0-9]\] components|successfully started \[[0-9] out of [0-9]\] components' 

關於你的編輯,我會去用下面的代碼:

sudo tail -f /opt/bmc/ao/cdp/tomcat/logs/grid.log | while read line; do 

    if $(echo "$line" | grep -E 'successfully started \[[0-9] out of [0-9]\] components|successfully started \[[0-9] out of [0-9]\] components'); then 
     (echo "CDP RESTARTS"; echo; echo "$line") | mail -s "BAOCDP AUTO RESTART" [email protected] 

     break 
    fi 

done 

除了放回了tail屬於它的地方,我也簡化了if的條件:grep將返回1當且僅​​當它匹配,因此它可以用作條件本身。

+0

謝謝,我會嘗試使用$ line並再次運行腳本 –

+0

@H .Birdi另一點:它看起來像你的腳本將永遠運行,爲每一個不匹配正則表達式的新行顯示「失敗」,這聽起來很糟糕。你可能想要一旦設置郵件就退出如果腳本只有在服務器啓動之前才運行)或者刪除'echo「FAIL」'(如果腳本永遠在後臺運行,發送每次服務器啓動時都會收到郵件) – Aaron

+0

我有失敗選項,因爲如果它與啓動的組件不匹配,那麼它會說它失敗......是否有另一種方法來執行此操作?郵件發送後我應該把EXIT 0? –