title: Bash: Breaking out of IF loop in FOR loop
body: <p>I am trying to combine a FOR loop (that iterates over IP addresses) and an IF loop (that uses nc to check for a successful ssh connection before moving on).</p>
  
  <p>I have an array ${INSTANCE_IPS[@]} with the IP addresses in it (at the moment it contains 2 IP Addresses). Here is the code:</p>
  
  <pre><code>while [ $ITERATION -le 30 ]
  do
      for instance in ${INSTANCE_IPS[@]}
      do    
          nc -w 2 $instance 22 &gt; /dev/null
              if [ $? -eq 0 ]
              then echo "connection succeeded to $instance"
              else
                  ITERATION=$((ITERATION+1))
                  echo ITERATION=$ITERATION
                  echo "[info] connection to $instance unsuccessful. trying again. iteration=$ITERATION"
                  sleep 20
              fi
      done
  done
  </code></pre>
  
  <p>The 'else' statement in the IF loop works fine. It is the 'then' statement I am having problems with... I don't know how to break out of the IF loop once the connections are successful. Here's an example output when I run the above:</p>
  
  <pre><code>connection succeeded to 10.11.143.171
  connection succeeded to 10.11.143.170
  connection succeeded to 10.11.143.171
  connection succeeded to 10.11.143.170
  connection succeeded to 10.11.143.171
  connection succeeded to 10.11.143.170
  </code></pre>
  
  <p>If I use <code>break</code> after <code>then echo "connection succeeded to $instance</code> then it only iterates through 1 IP address and never breaks out:</p>
  
  <pre><code>connection succeeded to 10.11.143.171
  connection succeeded to 10.11.143.171
  connection succeeded to 10.11.143.171
  </code></pre>
  
  <p>Ideally I think the best thing to do would be to query the number of elements in the array, then perform a netcat connection an increment some value by 1 until it equals the number of elements in the array, but I'm really not sure how to dot that.</p>
  
  <p>Any help is appreciated :) Please let me know if you need any more information.</p>
  
  <p>Cheers</p>