2015-12-02 17 views
5

我有一個bash腳本,它會經歷一個ip列表,並逐個ping它們。如果對每一個ping退出狀態是0,則呼應的節點啓動,否則節點就弄傷我能得到這個工作完美,但是當bash腳本結束退出狀態始終爲0使用while循環時的Bash退出狀態

我試圖實現的是,例如,如果第三個失敗,則通過列表繼續執行5個ip,然後檢查剩餘的腳本,但一旦腳本結束時拋出非0的退出狀態並輸出哪個ip失敗。

cat list.txt | while read -r output 
do 
    ping -o -c 3 -t 3000 "$output" > /dev/null 
    if [ $? -eq 0 ]; then 
    echo "node $output is up" 
    else 
    echo "node $output is down" 
    fi 
done 

在此先感謝!

回答

8

你的第一個問題是,通過做cat file | while read你已經在其自己的子shellhell中產生了while。它設置的任何變量將僅存在於該循環中,因此保留一個值將很困難。 More info on that issue here.

如果使用while read ... done < file它會正常工作。製作一個退出狀態標誌,默認爲零,但如果發生任何錯誤,將其設置爲1。將其用作腳本的退出值。

had_errors=0 

while read -r output 
do 
    ping -o -c 3 -t 3000 "$output" > /dev/null 
    if [ $? -eq 0 ]; then 
     echo "node $output is up" 
    else 
     echo "node $output is down" 
     had_errors=1 
    fi 
done < list.txt 

exit $had_errors 
+0

這看起來正在做我在找的東西。我不知道第一個問題,我明白。謝謝! – user2683183

+0

'cmd;如果[$? -eq 0];然後'幾乎**總是**更好地替換爲'if cmd; then'。 –