home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Unix Power ToolsUnix Power ToolsSearch this book

31.6. Loop Control: break and continue

Normally a for loop (Section 35.21) iterates until it has processed all its word arguments. while and until loops (Section 35.15) iterate until the loop control command returns a certain status. But sometimes -- for instance, if there's an error -- you want a loop to immediately terminate or jump to the next iteration. That's where you use break and continue, respectively.

break terminates the loop and takes control to the line after done. continue skips the rest of the commands in the loop body and starts the next iteration. Here's an example of both. An outer loop is stepping through a list of directories. If we can't cd to one of them, we'll abort the loop with break. The inner loop steps through all entries in the directory. If one of the entries isn't a file or isn't readable, we skip it and try the next one.

'...' Section 28.14, || Section 35.14, * Section 1.13, test Section 35.26

for dir in `find $HOME/projdir -type d -print`
    cd "$dir" || break
    echo "Processing $dir"
    for file in *
        test -f "$file" -a -r "$file" || continue
            ...process $dir/$file...

With nested loops (like the file loop above), which loop is broken or continued? It's the loop being processed at that time. So, the continue here restarts the inner (file) loop. The break terminates the outer (directory) loop -- which means the inner loop is also terminated. Note also that the -print argument to find is often redundant in the absence of another expression, depending on your version of find.

Here we've used break and continue within for loops, after the shell's || operator. But you can use them anywhere within the body of any loop -- in an if statement within a while loop, for instance.

-- JP

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.