next up previous
Next: Briefly About Linux Up: Conditional Statements Previous: The case statement

The for statement

The for loop notation has the general form:
for var in list-of-words
do
commands
done

commands is a sequence of one or more commands separated by a newline or ; (semicolon).

The reserved words do and done must be preceded by a newline or ; (semicolon). Small loops can be written on a single line. For example:
for var in list; do commands; done

This is a simple example of a for loop and a 'command substitution':
for i in `ls `
do
echo "the name of the file is $i"
done

In this example, the command ls is executed first, since it is used inside back-quotes. Then the values are substituted to i and proper message is printed. Suppose that the result of the ls command is:
first
test.sh
Then the output from the for loop is:
the name of the file is first
the name of the file is test.sh

For information on while loop and other useful commands used refer to the UNIX in a nutshell book.


next up previous
Next: Briefly About Linux Up: Conditional Statements Previous: The case statement
Instructional Support Group 2008-08-05