Linux Know-How provides a collection of introductory texts on often needed Linux skills. |
![]() |
Home ![]() ![]() ![]() |
||||
See also: I/0 redirection and loops | ||||
![]() ![]() ![]() ![]() ![]() ![]() ![]() |
||||
Break and continueThe break built-inThe break statement is used to exit the current loop before its normal ending. This is done when you don't know in advance how many times the loop will have to execute, for instance because it is dependent on user input. The example below demonstrates a while loop that can be interrupted. This is a slightly improved version of the wisdom.sh script from Section 9.2.2.3.
Mind that break exits the loop, not the script. This can be demonstrated by adding an echo command at the end of the script. This echo will also be executed upon input that causes break to be executed (when the user types "0"). In nested loops, break allows for specification of which loop to exit. See the Bash info pages for more. The continue built-inThe continue statement resumes iteration of an enclosing for, while, until or select loop. When used in a for loop, the controlling variable takes on the value of the next element in the list. When used in a while or until construct, on the other hand, execution resumes with TEST-COMMAND at the top of the loop. ExamplesIn the following example, file names are converted to lower case. If no conversion needs to be done, a continue statement restarts execution of the loop. These commands don't eat much system resources, and most likely, similar problems can be solved using sed and awk. However, it is useful to know about this kind of construction when executing heavy jobs, that might not even be necessary when tests are inserted at the correct locations in a script, sparing system resources.
This script has at least one disadvantage: it overwrites existing files. The noclobber option to Bash is only useful when redirection occurs. The -b option to the mv command provides more security, but is only safe in case of one accidental overwrite, as is demonstrated in this test:
The tr is part of the textutils package; it can perform all kinds of character transformations.
|
||||
Home ![]() ![]() ![]() |