PreviousNext

The foreach Loop

When you want to perform a given operation on each element in a list, use the foreach command. Remember that a list is a collection of objects, or things typed in by you or returned from a command. The syntax is:

foreach variable_name list body

The foreach command consists of a list, a script body, and a variable that represents each element of the list, in turn. The command runs the script body on the element represented by the variable and then sets the variable to be the next element in the list.

The following foreach command example could be part of a script that manages hosts in a DCE cell. This script fragment removes the host principal name from the registry if a failure occurs while configuring the host in the cell. The foreach command looks at each principal name in the cell. If the string commands find the hostname listed in the output from principal catalog, the script deletes the principal name from the registry.

foreach princ [principal catalog -simplename] {
if {[string match $host_name [string range $princ 0 \
[expr [string length $host_name] - 1]]] == 1} {
principal delete $princ
}
}

Keep in mind that loops return their results to the interpreter, not to stdout. You need to take extra steps to send the results to stdout. The next example uses a puts command to send the results of the foreach loop to stdout.

foreach i [group list subsys/dce/dts-servers] {
puts [principal show $i]
}

You can also append all the results together into a variable in a script, or you can use lappend to append the results as separate list elements.

foreach i [group list subsys/dce/dts-servers] {
append result [principal show $i]
}
return $result