x
Loading
 Loading
Hello, Guest | Login | Register

Loops at Last

On a cross-country plane trip, you sometimes reach an altitude from which you can see where you’ve been. This month’s column on the topic of loops is a high-altitude point in our exploration of the bash shell. Much of what has been explained so far is a prerequisite for understanding loops. Computers are powerful because they can quickly and accurately perform repetitive operations, and the loop is the shell construct that puts this power right into your hands.

On a cross-country plane trip, you sometimes reach an altitude from which you can see where you’ve been. This month’s column on the topic of loops is a high-altitude point in our exploration of the bash shell. Much of what has been explained so far is a prerequisite for understanding loops. Computers are powerful because they can quickly and accurately perform repetitive operations, and the loop is the shell construct that puts this power right into your hands.

The while Command

The shell provides three different loop commands:

  • while
  • until
  • for

The while command, the simplest of the three, has this form:

while test do body done 

Notice that the command includes three keywords (while, do, and done) and two user-supplied components (test and body). The command is often written as shown, on four lines. However, the command can also be written on a single line by inserting semi-colons that enable the shell to parse it:

while test; do body; done 

Newbies Fig1
Figure One: The syntactic structure of the while command.

Computer scientists sometimes refer to keywords and punctuation as syntactic sugar. In this respect, the while command is indeed sugar-laden. Figure One presents the command’s syntax visually, using a simple railroad track…

Please log in to view this content.

Not Yet a Member?

Register with LinuxMagazine.com and get free access to the entire archive, including:

  • Hands-on Content
  • White Papers
  • Community Features
  • And more.
Already a Member?
Log in!
Username

Password

Remember me

Forgotten your password?
Forgotten your username?
Read More
  1. Helpful Tools for Software Developers
  2. The Github Hall of Fame
  3. Book'em, Github.
  4. This Week on Github: Stupid Ruby Tricks
  5. A Veritable Scatter Shot!
Follow Linux Magazine
Rackspace