Break is used In scripting to stop the execution of a loop before its completion .
For e.g.
In the above loop the number of iterations are 10 unless the user enters "n" as the input,choosing the stop the loop before 10 iterations.
On receiving "y" as input , break is called which stops the execution of loop and breaks out of it before it completes its 10 iterations .
break can also be used to get out of multiple loops at the same time, by passing the number of loops to break out of as an option i.e.
Where n is the number of levels of loop to break out of, it has to be a positive number.
For example, in the following script there are three levels of loop and the break is in the inner most loop, which is the level 3.
When the user enters "y" to break out of the loop, we call break 2 signifying that we want to break out of 2 levels of the loop and the control of the script goes to the outermost loop.
multi_break.sh
Save the script and give it execute permissions
execute the script
Output:
From the above output we can see that on entering "y" the control directly goes to the outermost loop that is the level 1, thus breaking out of two levels of the loop.
For e.g.
In the above loop the number of iterations are 10 unless the user enters "n" as the input,choosing the stop the loop before 10 iterations.
On receiving "y" as input , break is called which stops the execution of loop and breaks out of it before it completes its 10 iterations .
break can also be used to get out of multiple loops at the same time, by passing the number of loops to break out of as an option i.e.
Where n is the number of levels of loop to break out of, it has to be a positive number.
For example, in the following script there are three levels of loop and the break is in the inner most loop, which is the level 3.
When the user enters "y" to break out of the loop, we call break 2 signifying that we want to break out of 2 levels of the loop and the control of the script goes to the outermost loop.
multi_break.sh
Save the script and give it execute permissions
execute the script
Output:
From the above output we can see that on entering "y" the control directly goes to the outermost loop that is the level 1, thus breaking out of two levels of the loop.
No comments:
Post a Comment