Hello Linux-fanatics, In our last tutorial we learned to use while & until loops in our scripts & now in this tutorial we will discuss to control our loops by using break & continue commands.
Most of the time when running our script, we need not make any changes to it but sometimes need arises to control our loops. To achieve loop control, we use break or continue command depending on the need. Let’s discuss both commands in brief,
Break command is used to exit out of current loop completely before the actual ending of loop. Its comes handy when we don’t have prior knowledge of how long will the loop last like when we user’s input is required.
Let’s see a simple example script,
We can also use break command in scripts with multiple loops. If we want to exit out of current working loop whether inner or outer loop, we simply use break but if we are in inner loop & want to exit out of outer loop, we use break 2.
Script will start with a=1 & will move to inner loop and when it reaches b=4, it will break the outer loop.
In this same script, you can use break only instead of break 2, to break inner loop & see how it affects the output.
Continue command is used in script to skip current iteration of loop & continue to next iteration of the loop.
We can also use continue command in similar way to break command for controlling multiple loops.
This concludes our tutorial on controlling loops using break & continue command. Please share your queries/suggestions in the comment box down below.ADIOS!!!