user3086014
user3086014

Reputation: 4511

code goes in an infinite loop

I have a code in shell script as follows:

    # 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 

This code sometimes work fine, sometimes it dont works fine. It goes to an infinite loop. I want to do something like this i want to check the output of ec2-describe-snapshot that if snaphost are in pending state. if yes it should wait until all the snapshots are completed.

The output of ec2-describe-snapshots is

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)

Upvotes: 1

Views: 212

Answers (1)

janos
janos

Reputation: 124656

The program will loop forever if there is at least one pending snapshot. Perhaps it will be helpful to print what are those pending snapshots, by changing the script like this:

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

But surely that doesn't happen really infinitely. You probably just have to wait. When there are no more pending snapshots, the loop will stop. Really.

Btw here's a slightly improved version of your script. It's equivalent to yours, just the syntax is improved to remove some unnecessary stuff and replace old style writing with modern methods:

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 

Upvotes: 3

Related Questions