34.6. Oddities

Can a script recursively call itself? Indeed.


Example 34-6. A script that recursively calls itself

   1 #!/bin/bash
   2 # recurse.sh
   3 
   4 #  Can a script recursively call itself?
   5 #  Yes, but this is of little or no practical use
   6 #+ except perhaps as a "proof of concept".
   7 
   8 RANGE=10
   9 MAXVAL=9
  10 
  11 i=$RANDOM
  12 let "i %= $RANGE"  # Generate a random number between 0 and $MAXVAL.
  13 
  14 if [ "$i" -lt "$MAXVAL" ]
  15 then
  16   echo "i = $i"
  17   ./$0             #  Script recursively spawns a new instance of itself.
  18 fi                 #  Each child script does the same, until
  19                    #+ a generated $i equals $MAXVAL.
  20 
  21 #  Using a "while" loop instead of an "if/then" test causes problems.
  22 #  Exercise for the reader: Explain why.
  23 
  24 exit 0

Caution

Too many levels of recursion can exhaust the script's stack space, causing a segfault.