Although tests are great for deciding which parts of a script to execute, most scripts need to execute the same commands multiple times.
They need to
loop
, or go back and repeat some commands.
For example, if you needed to process information from a set of lines in a file, you could repeat the same commands over and over again in a script, once for each line of the file you had to process. A
loop[1] (often combined with a variable) enables you to write the commands once and have them repeated for each line of the file. By using a control structure, or looping structure, control of which line of the script is being executed can return to an earlier part of the script file rather than just continuing sequentially to the end of the script. . This flow control can be done in several ways. A block of commands (a portion of a shell script) can be repeated:
You can use different keywords in a shell script to set up each of these types of loops, or control structures. Many control structures rely on a test, much as an if keyword uses a test to make a decision.
Some of the keywords are for control structures that you will learn about later in this course, including loops called for loops, while loops, and until loops.
Selecting the best control structure and forming a good test to set it in motion are a large part of effective shell programming.
Regular expressions are used to express patterns in tests and control structures. The next lesson introduces you to them.