Break and Continue Keywords in Linux with Examples
Both “break” and “continue” are used to transfer control of the program to another part of the program. It is used within loops to alter the flow of the loop and terminate the loop or skip the current iteration.
The break statement is used to terminate the loop and can be used within a while, for, until, and select loops.
break [N] // N is the number of nested loops. // This parameter is optional. // By default the value of N is 1.
Using break command in a loop.
It can be seen that when the value of i is 3, the loop execution is terminated and hence i is only printed upto 2.
Example: Using break with the value of N. Consider an example:
for i in `seq 1 5` do for j in `seq 1 5` do if(( $j== 2 )) then break 2 fi echo "value of j is $j" done echo "value of i is $i" done
As the value of break is 2, when the value of j is 2, both the loops are exited in a single step. So, the only value of j is printed when it was 1.
Continue is a command which is used to skip the remaining command inside the loop for the current iteration in for, while, and until loop.
continue [N] // the optional parameter N specifies the nth enclosing loop to continue from. // This parameter is optional. // By default the value of N is 1.
Using break command in a loop
Example: Using continue with the value of N. Consider an example:
for i in `seq 1 5` do for j in `seq 1 5` do if(( $j== 2 )) then continue 2 fi echo "value of j is $j" done echo "value of i is $i" done
Continue skips both the loop when the value of j is 2 and hence, the code only executes when the value of j is 1.
Difference between break and continue
|1||It terminates the execution of the loop for all the remaining iterations.||It skips the execution of the loop for only the current iteration.|
|2||It allows early termination of the loop.||It allows early execution of the next iteration.|
|3||It stops the execution of loops.||It stops the execution of the loop only for the current iteration.|
|4||The code after the loop which was terminated is continued.||The code in the loop continues its execution skipping the current iteration.|