Posted by Kieren Searle on the 04/10/08

How to exit a loop in bash

If you want to exit out of a loop but want the script to continue running from after the loop then you need to use the break statement;

Code:

for (( i=0; i<5; i+=1 )) {
  if [[ $i -eq 3 ]]
    then
      break
    else
      echo "i: $i"
  fi
}

Output:

i: 0
i: 1
i: 2

If you have two loops within each other only the current loop will exit with break. In the following example when the first break is called, when j=0 and i=3, only the second for loop exits and the outer one continues.

Code:

for (( j=0; j<2; j+=1 )) {
  for (( i=0; i<5; i+=1 )) {
    if [[ $i -eq 3 ]]
      then
        break
      else
        echo "j: $j"
        echo "i: $i"
        echo ""
    fi
  }
}

Output:

j: 0
i: 0

j: 0
i: 1

j: 0
i: 2

j: 1
i: 0

j: 1
i: 1

j: 1
i: 2

Trackback address for this post

An unexpected error has occurred!

If this error persists, please report it to the administrator.

Go back to home page

Additional information about this error:

MySQL error!

Can't open file: 'evo_plugin_captcha_img_17_data.MYI' (errno: 145)(Errno=1016)

Your query:

SELECT COUNT(*) 
FROM evo_plugin_captcha_img_17_data
WHERE cpt_public = "8a9f0bce6d686cf78e3600f54c75c6a5"