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 pdksh and 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 parameter is assigned to the variable curvar.

This form can also be written as follows:

for curvar in [email protected] do statements done

Remember that [email protected] 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.

Under tcsh, the for statement is called foreach. The format is as follows:

foreach curvar (list) statements end

In this form, statements are executed once for each value in list, and, for each iteration, the current value of list is assigned to curvar.

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 pdksh and bash:

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.

The same example in tcsh is as follows:

#!/bin/tcsh foreach filename (Vbin/lsN)

cp $filename backup/$filename if ($? != 0) then echo "copy for $filename failed" endif end

Was this article helpful?

0 0

Post a comment