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.

This construct tests for a condition at the top of a loop, and keeps looping as long as that condition is<br />

false (opposite of while loop).<br />

until [condition−is−true]<br />

do<br />

command...<br />

done<br />

Note that an until loop tests for the terminating condition at the top of the loop, differing from a<br />

similar construct in some programming languages.<br />

As is the case with for/in loops, placing the do on the same line as the condition test requires a<br />

semicolon.<br />

until [condition−is−true] ; do<br />

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

Example 10−18. until loop<br />

#!/bin/bash<br />

until [ "$var1" = end ] # Tests condition here, at top of loop.<br />

do<br />

echo "Input variable #1 "<br />

echo "(end to exit)"<br />

read var1<br />

echo "variable #1 = $var1"<br />

done<br />

exit 0<br />

10.2. Nested Loops<br />

A nested loop is a loop within a loop, an inner loop within the body of an outer one. What happens is that the<br />

first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the<br />

outer loop triggers the inner loop again. This repeats until the outer loop finishes. Of course, a break within<br />

either the inner or outer loop may interrupt this process.<br />

Example 10−19. Nested Loop<br />

#!/bin/bash<br />

# Nested "for" loops.<br />

outer=1<br />

# Set outer loop counter.<br />

# Beginning of outer loop.<br />

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

do<br />

echo "Pass $outer in outer loop."<br />

echo "−−−−−−−−−−−−−−−−−−−−−"<br />

inner=1<br />

# Reset inner loop counter.<br />

# Beginning of inner loop.<br />

Chapter 10. Loops and Branches 113

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

Saved successfully!

Ooh no, something went wrong!