PreviousNext

Terminating Loops with continue and break

The continue and break commands terminate loops started with the while, for, and foreach commands.

Use the continue command to terminate the current iteration of a loop. For instance, your loop can test for, and selectively ignore particular elements in a list while continuing to operate on the rest of the elements. Use the break command to immediately terminate loop execution.

The following example script fragment is a foreach command loop that includes continue and break commands. The foreach command looks through all the DTS servers in a cell until it finds one that is a time provider (a time provider is a special DTS server that receives time from an external time source). If the first server in the list (created by the dts catalog operation) returns output from a dts show operation, the continue command invokes the next lines in the script which search the output for the {provider yes} attribute and value. If the provider attribute (examined by the attrlist getval operation) is yes, the script sets the server variable to be the name of that DTS server and the break command terminates the entire foreach loop.

foreach s [dts catalog] {
if {[catch {dts show $s} dts_sh_out] != 0} {
continue
}
set p [attrlist getval $dts_sh_out -type provider]
if {[string match $p "yes"] == 1} {
set provider "yes"
set server $s
break
}
set provider "no"
}