Bash Break Statement

The Bash Break statement helps in terminating the current loop and passing program control to the command that follows the terminated loop. We use it to exit from a while, until, for or select loops. The syntax of the Break statement is: break[n]. Where [n] is an optional argument that must be greater than or equal to 1. Let’s understand the Break statement with an example. Here is a simple program with a for loop that will iterate over a range of values from 1-20 with an increment of 2. The conditional statement in the third line will check the expression and when val=9 is true, the break statement will run and the loop will be terminated.

Further, if you want to exit from a second loop or outer loop then you can use ‘break 2’. This will tell that loop too needs to be terminated.

Bash Continue

We use the Break statement to exit the entire loop when a condition is satisfied. What if you want to skip a particular block of code instead of exiting the entire loop? In such conditions, we use the Bash Continue statement. The Continue statement lets you skip the execution of a code block when the condition is satisfied or we can say that statement skips the remaining part of the code for the current iteration and passes control to the next iteration of the loop. The syntax of the Continue statement is: continue [n]. Again [n] is an optional argument that can be greater than or equal to 1. Let’s understand the Continue statement with an example. Here we have a simple program and in that when the current iterated item will be equal to 2, the continue statement will return to the beginning of the loop and continue with the next iteration.

The output of this program will be as follows: