【问题标题】:code goes in an infinite loop代码进入无限循环
【发布时间】:2013-12-30 10:50:29
【问题描述】:

我在 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-describe-snapshots 的输出是

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)

【问题讨论】:

  • 提示,也许在你的脚本中使用logger
  • 那是什么?我什么都没得到
  • 您的echo 命令是否显示有非零数量的快照等待完成?或者你看到There are 0 snapshots waiting for completion 并且它还在循环?
  • no 不显示非零。喜欢There are 1 snapshots waiting for completion.
  • 这确实意味着至少有一个待处理的快照...

标签: linux shell amazon-ec2


【解决方案1】:

如果至少有一个待处理的快照,程序永远循环。通过像这样更改脚本,打印那些待处理的快照可能会有所帮助:

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 

【讨论】:

  • 在问题中查看我更新的代码。你认为它会起作用吗?
  • 你给了我我写的确切答案
  • 是的,我的代码是echo "There are $command snapshots waiting for completion." sleep 5 # Re run the command. command=ec2-describe-snapshots |待处理 | wc -l`
  • 现在当我运行我的代码(在顶部给出)它工作正常!我该怎么办
  • 为了清楚起见,我添加了一个完整版本。你会看到一条你没有的线。这就是我的意思,但你没有正确阅读。顺便说一句,您的脚本已经很好了,这里没有问题,您只需等待快照完成,显然这有时可能需要很长时间。
猜你喜欢
  • 2014-05-14
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
相关资源
最近更新 更多