2013-12-12 129 views
1

我在shell腳本中的代碼如下:代碼放在一個無限循環

# Setup the command. 
command=`ec2-describe-snapshots | grep pending | wc -l` 

# Check if we have any pending snapshots at all. 
if [ $command == "0" ] 
then 
     echo "No snapshots are pending." 
     ec2-describe-snapshots 
else 
     # Wait for the snapshot to finish. 
     while [ $command != "0" ] 
     do 
       # Communicate that we're waiting. 
       echo "There are $command snapshots waiting for completion." 
       sleep 5 

       # Re run the command. 
       command=`ec2-describe-snapshots | grep pending | wc -l` 
     done 

     # Snapshot has finished. 
    echo -e "\n" 
     echo "Snapshots are finished." 
fi 

此代碼有時正常工作,有時不工作正常。它走向一個無限循環。我想要做這樣的事情,我想查看ec2-describe-snapshot的輸出,如果snaphost處於掛起狀態。如果是,則應等到所有快照完成。

的輸出EC2-描述的快照是

SNAPSHOT snap-104ef62e vol-a8 completed 2013-12-12T05:38:28+0000 100% 109030037527 20 2013-12-12: Daily Backup for i-3ed09 (VolID:vol-aecbbcf8 InstID:i-3e2bfd09) 
SNAPSHOT snap-1c4ef622 vol-f0 pending 2013-12-12T05:38:27+0000 100% 109030037527 10 2013-12-12: Daily Backup for i-260 (VolID:vol-f66a0 InstID:i-2601) 
+0

提示,或者用'logger'你的腳本中。 –

+0

那是什麼?我沒有收到任何東西 – user3086014

+0

您的'echo'命令是否顯示等待完成的非零數量的快照?或者你看到「有0個等待完成的快照」,它仍然循環? –

回答

3

程序循環永遠如果有至少一個未決快照。也許這將有助於打印的內容是那些懸而未決的快照,通過改變這樣的腳本:

echo "There are $command snapshots waiting for completion." 
ec2-describe-snapshots | grep pending 

但可以肯定的是並沒有真正無限發生。你可能只需等待。當沒有更多掛起的快照時,循環將停止。真。

順便提一下,這是一個略有改進的腳本版本。這相當於給你的,只是語法進行改進,去除一些不必要的東西,並用現代的方法取代舊的寫作風格:

command=$(ec2-describe-snapshots | grep pending | wc -l) 

# Check if we have any pending snapshots at all. 
if [ $command = 0 ] 
then 
     echo "No snapshots are pending." 
     ec2-describe-snapshots 
else 
     # Wait for the snapshot to finish. 
     while [ $command != 0 ] 
     do 
       # Communicate that we're waiting. 
       echo "There are $command snapshots waiting for completion." 
       ec2-describe-snapshots | grep pending 
       sleep 5 

       # Re run the command. 
       command=$(ec2-describe-snapshots | grep pending | wc -l) 
     done 

     # Snapshot has finished. 
     echo 
     echo "Snapshots are finished." 
fi 
+0

在問題中查看我的更新代碼。你認爲它會起作用嗎? – user3086014

+0

你給我的確切答案是我寫的 – user3086014

+0

什麼?一點也不。你讀的是對的嗎? – janos