Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1

The for Statement


You use the for statement 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:


Click here to view code image
for curvar in list
do
statements
done


You should use this format 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:


Click here to view code image
for curvar
do
statements
done


In this format, 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. You can also
write this format as follows:


Click here to view code image
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.


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


Click here to view code image
foreach curvar (list)
statements
end


In this format, statements are executed once for each value in list, and,

Free download pdf