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...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

semicolon.<br />

while [condition] ; do<br />

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

Note that certain specialized while loops, as, for example, a getopts construct, deviate somewhat from<br />

the standard template given here.<br />

Example 10−14. Simple while loop<br />

#!/bin/bash<br />

var0=0<br />

LIMIT=10<br />

while [ "$var0" −lt "$LIMIT" ]<br />

do<br />

echo −n "$var0 " # −n suppresses newline.<br />

var0=`expr $var0 + 1` # var0=$(($var0+1)) also works.<br />

done<br />

echo<br />

exit 0<br />

Example 10−15. Another while loop<br />

#!/bin/bash<br />

echo<br />

while [ "$var1" != "end" ] # while test "$var1" != "end"<br />

do<br />

# also works.<br />

echo "Input variable #1 (end to exit) "<br />

read var1<br />

# Not 'read $var1' (why?).<br />

echo "variable #1 = $var1" # Need quotes because of "#".<br />

# If input is 'end', echoes it here.<br />

# Does not test for termination condition until top of loop.<br />

echo<br />

done<br />

exit 0<br />

A while loop may have multiple conditions. Only the final condition determines when the loop<br />

terminates. This necessitates a slightly different loop syntax, however.<br />

Example 10−16. while loop with multiple conditions<br />

#!/bin/bash<br />

var1=unset<br />

previous=$var1<br />

while echo "previous−variable = $previous"<br />

Chapter 10. Loops and Branches 111

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

Saved successfully!

Ooh no, something went wrong!