LDP/LDP/guide/docbook/abs-guide/recurse.sh

31 lines
726 B
Bash
Raw Normal View History

2001-10-15 14:28:18 +00:00
#!/bin/bash
# recurse.sh
# Can a script recursively call itself?
2002-06-03 14:35:48 +00:00
# Yes, but is this of any practical use?
2003-06-30 16:57:44 +00:00
# (See the following.)
2001-10-15 14:28:18 +00:00
RANGE=10
MAXVAL=9
i=$RANDOM
2003-11-03 16:25:16 +00:00
let "i %= $RANGE" # Generate a random number between 0 and $RANGE - 1.
2001-10-15 14:28:18 +00:00
if [ "$i" -lt "$MAXVAL" ]
then
echo "i = $i"
./$0 # Script recursively spawns a new instance of itself.
fi # Each child script does the same, until
#+ a generated $i equals $MAXVAL.
# Using a "while" loop instead of an "if/then" test causes problems.
2002-04-01 16:04:17 +00:00
# Explain why.
2001-10-15 14:28:18 +00:00
exit 0
2004-10-03 17:40:48 +00:00
# Note:
# ----
# This script must have execute permission for it to work properly.
# This is the case even if it is invoked by an "sh" command.
# Explain why.