KOOLz KOOLz - 27 days ago 8
Bash Question

I do not understand the break command

in:

#!/bin/sh

for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
fi
done
done


the output is:

1 0
1 5


and then script stops.

how ever if the break command's argument (2) is removed, the output is:

1 0
1 5
3 0
3 5


What i am asking is why
3 0
and
3 5
are printed, when the script is conditioned not to break? script didn't print
2 0
and
2 5
, and
3 0
and
3 5
should signal a break as well...

Answer

To summarize the comments, there were two issues:

  • Why is 3 0 printed after a break, but not after break 2?

This was because the condition ([ $var1 -eq 2 -a $var2 -eq 0 ]) checked for equality rather than -ge, greater or equal. With -ge there will be no echos where both numbers are greater.

The break 2 instead exited both loops, thereby giving the same effect in this particular case. If the loop had been for var1 in 1 2 0, break 2 would have also prevented 0 0 from showing up since both loops would have been stopped.

  • Why is 2 5 not printed after a brake?

This is because the entire inner loop stops on a break, so no other iterations will have their chance to echo. To instead skip the current iteration and immediately try the next one, use continue.