What is the difference between `break` and `exit`?
Do `break` and `continue` work in `select` loops?
Can I use `break` and `continue` in the same loop?
For Bash:
$ help break
break: break [n]
Exit for, while, or until loops.
Exit a FOR, WHILE or UNTIL loop. If N is specified, break N enclosing
loops.
Exit Status:
The exit status is 0 unless N is not greater than or equal to 1.
The error message you are seeing is issued by Bash. What is the context in which you are trying to understand "break"?
In C, break is a keyword. See this wikibook for more information. In part, it says:
A break statement will immediately exit the enclosing loop.
If I got your question right, what you are after is:
man bash
alternatively you can also issue:
man bash | grep -C5 "break [n]"
EDIT: Sorry, I missed your note about not being the bash break. :-| However I can't reproduce the error message you get. I get instead:
bash: break: only meaningful in a `for', `while', or `until' loop
What version of ubuntu do you use? What version of bash? Mine is version 4.0.33(1)-release (x86_64-pc-linux-gnu)... I am asking just in case the two different messages are both from bash but from different versions...
What does
which break
output to you? If it is a standalone program you will get the directory where the executable is located and thus probably be able to understand what installation is part of. If it is a bash (ot other shell) command it will silently fail (no output).
The optional argument to break tells it which loop to break out of. If the argument is omitted, it breaks out of the innermost loop. With an argument n it breaks out of the nth enclosing loop.
So break 2 breaks out of the for var1 loop, because it's the 2nd enclosing loop. If you change it to break, it just breaks out of the for var2 loop, so it goes to the next iteration of for var1.
To summarize the comments, there were two issues:
- Why is
3 0printed after abreak, but not afterbreak 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 5not printed after abrake?
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.