Loops

There are three looping constructs, the while, until, and for loops, which can be used to repeatedly execute a sequence of shell commands.

While Loop

The while loop repeatedly executes a compound-list while another compound-list has a zero exit status; it has the form,

while-loop:
while compound-list
do
   compound-list
done

The while compound-list is executed; if it has exit status zero, the do compound-list is executed and the process repeats.

Exit Status

The exit status of the while command is the exit status of the last do compound-list that was executed, otherwise zero.

Until Loop

The until loop is identical to the while loop except that it executes a compound-list until another compound-list has a zero exit status; it has the form,

until-loop:
until compound-list
do
   compound-list
done

Exit Status

As with the while loop, the exit status of the while command is the exit status of the last do compound-list that was executed, otherwise zero.

For Loop

The for loop repeatedly executes a compound-list for each member of a list of items; it has the form,

for-loop
for name [ in [word ... ]]
do
   compound-list
done

The list of words following in are expanded to generate a list of items. On each iteration, the variable name is set to the next item and the compound-list is executed, until the list of items is exhausted.

Exit Status

The exit status of a for command is the exit status of the last command that executes, or zero if there are no items.

Warning

Notice that the exit status of all the looping constructs is 0 if the loop body is never executed.