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.

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

# Thank you, S.C.<br />

34.4. Recursion<br />

Can a script recursively call itself? Indeed.<br />

Example 34−6. A (useless) script that recursively calls itself<br />

#!/bin/bash<br />

# recurse.sh<br />

# Can a script recursively call itself?<br />

# Yes, but is this of any practical use?<br />

# (See the following script.)<br />

RANGE=10<br />

MAXVAL=9<br />

i=$RANDOM<br />

let "i %= $RANGE" # Generate a random number between 0 and $MAXVAL.<br />

if [ "$i" −lt "$MAXVAL" ]<br />

then<br />

echo "i = $i"<br />

./$0 # Script recursively spawns a new instance of itself.<br />

fi<br />

# Each child script does the same, until<br />

#+ a generated $i equals $MAXVAL.<br />

# Using a "while" loop instead of an "if/then" test causes problems.<br />

# Explain why.<br />

exit 0<br />

Example 34−7. A (useful) script that recursively calls itself<br />

#!/bin/bash<br />

# pb.sh: phone book<br />

# Written by Rick Boivie, and used with permission.<br />

# Modifications by document author.<br />

MINARGS=1 # Script needs at least one argument.<br />

DATAFILE=./phonebook<br />

PROGNAME=$0<br />

E_NOARGS=70 # No arguments error.<br />

if [ $# −lt $MINARGS ]; then<br />

echo "Usage: "$PROGNAME" data"<br />

exit $E_NOARGS<br />

fi<br />

if [ $# −eq $MINARGS ]; then<br />

grep $1 "$DATAFILE"<br />

else<br />

Chapter 34. Miscellany 341

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

Saved successfully!

Ooh no, something went wrong!