Книга: Fedora™ Unleashed, 2008 edition

The for Statement

The for Statement

The for statement is used to execute a set of commands once each time a specified condition is true. The for statement has a number of formats. The first format used by bash is as follows:

for curvar in list
do
 statements
done

This form should be used if you want to execute statements once for each value in list. For each iteration, the current value of the list is assigned to vcurvar. list can be a variable containing a number of items or a list of values separated by spaces. The second format is as follows:

for curvar
do
 statements
done

In this form, the statements are executed once for each of the positional parameters passed to the shell program. For each iteration, the current value of the positional para meter is assigned to the variable curvar.

This form can also be written as follows:

for curvar in $@
do
 statements
done

Remember that $@ gives you a list of positional parameters passed to the shell program, quoted in a manner consistent with the way the user originally invoked the command.

Suppose that you want to create a backup version of each file in a directory to a subdirectory called backup. You can do the following in bash:

#!/bin/sh
for filename in *
do
 cp $filename backup/$filename
 if [ $? -ne 0 ]; then
  echo "copy for $filename failed"
 fi
done

In the preceding example, a backup copy of each file is created. If the copy fails, a message is generated.

Оглавление книги


Генерация: 0.550. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз