9

I have a bash script which simply docker pushes an image:

docker push $CONTAINER_IMAGE:latest

I want to loop for 3 times when this fails. How should I achieve this?

22

Use for-loop and && break:

for n in {1..3}; do
    docker push $CONTAINER_IMAGE:latest && break;
done

break quits the loop, but only runs when docker push succeeded. If docker push fails, it will exit with error and the loop will continue.

  • 4
    Technically, OP wants it to loop three times when it fails. So, shouldn't the loop counter be 4? – RonJohn Jul 11 at 3:47
5

You can also use :

for n in {1..3}; do
     if docker push $CONTAINER_IMAGE:latest  
     then 
          break;
     fi
done

The then statement will be entered only if the docker command succeeds.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.