27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

##################################################################<br />

# Same loop, but substituting 'break' for 'continue'.<br />

a=0<br />

while [ "$a" −le "$LIMIT" ]<br />

do<br />

a=$(($a+1))<br />

if [ "$a" −gt 2 ]<br />

then<br />

break # Skip entire rest of loop.<br />

fi<br />

echo −n "$a "<br />

done<br />

echo; echo; echo<br />

exit 0<br />

The break command may optionally take a parameter. A plain break terminates only the innermost<br />

loop in which it is embedded, but a break N breaks out of N levels of loop.<br />

Example 10−21. Breaking out of multiple loop levels<br />

#!/bin/bash<br />

# break−levels.sh: Breaking out of loops.<br />

# "break N" breaks out of N level loops.<br />

for outerloop in 1 2 3 4 5<br />

do<br />

echo −n "Group $outerloop: "<br />

for innerloop in 1 2 3 4 5<br />

do<br />

echo −n "$innerloop "<br />

if [ "$innerloop" −eq 3 ]<br />

then<br />

break # Try break 2 to see what happens.<br />

# ("Breaks" out of both inner and outer loops.)<br />

fi<br />

done<br />

echo<br />

done<br />

echo<br />

exit 0<br />

The continue command, similar to break, optionally takes a parameter. A plain continue cuts short<br />

the current iteration within its loop and begins the next. A continue N terminates all remaining<br />

iterations at its loop level and continues with the next iteration at the loop N levels above.<br />

Chapter 10. Loops and Branches 115

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!