I decide to play around loop just to understand how loops work in bash. But I am the one who got played. All I know is the the break call helps to stop a particular loop
echo "For loop begins"
for (( a = 1; a < 10; a++ ))
do
echo -e "\tOuter loop ${a}"
for (( b = 1; b < 100; b++ ))
do
if [[ ${b} -gt 5 ]]
then
break 2
fi
echo -e "\t\tInner loop ${b}"
done
done
echo "For loop completed"
So fortunate that the break 2 call also breaks out of the outer loop.
I already tried cahanging my for loop to
for (( a = 1; a <= 10; a++ )) and the second one to for (( b = 1; b <= 100; b++ )) putting <= instead of < but I still get same output.
genius@GeniusDPhil-hp250g1notebookpc:~$ ./loop.sh
For loop begins
Outer loop 1
Inner loop 1
Inner loop 2
Inner loop 3
Inner loop 4
Inner loop 5
For loop completed
genius@GeniusDPhil-hp250g1notebookpc:~$
I was expecting the outer loop to run 10 times, does break also take me out of my outer loop? if yes how do I use break properly? if no the what's the issue?
NOTE: The programmer in me is 3 months old.
break 2, only 5 iterations of the inner loop, and one iteration of the outer loop will be executed. You forgot to explain what you want (please edit your question to add this) but if you want to break only the inner loop usebreak 1(or justbreak, it's the same).break [n]: Exit from within a for, while, until, or select loop. If n is specified, break n levels. n must be >= 1. If n is greater than the number of enclosing loops, all enclosing loops are exited. The return value is 0 unless n is not greater than or equal to 1.(( ...))for your arithmetic test:if (( b > 5 )); then..., instead of the[[ ${b} -gt 5 ]]conditional expression.if [[ ${b} -gt 5 ]]; then ... fidoes not count as a loop level.break nmeans break out ofnnesting levels of looping, notnnesting levels of loops or other kinds of statements. The defaultnis 1: break out of the inner-most enclosing loop.break 2means break out of the innermost enclosing loop and the one enclosing it, and so on.break 2before learning about justbreak? It's odd that the only thing wrong is that we have to delete the2in your script; what led you to add that?