24.2.1. Local variables and recursion.
Local variables are a useful tool for writing recursive code, but this practice generally involves a great deal of computational overhead and is definitely not recommended in a shell script.
Example 24-15. Recursion, using a local variable
# Does bash permit recursion?
# Well, yes, but...
# It's so slow that you gotta have rocks in your head to try it.
if [ -z "$1" ]
echo "Usage: `basename $0` number"
if [ "$1" -gt $MAX_ARG ]
echo "Out of range ($MAX_ARG is maximum)."
# Let's get real now.
# If you want greater range than this,
#+ rewrite it in a Real Programming Language.
# Variable "number" must be declared as local,
#+ otherwise this doesn't work.
if [ "$number" -eq 0 ]
factorial=1 # Factorial of 0 = 1.
let "decrnum = number - 1"
fact $decrnum # Recursive function call (the function calls itself).
let "factorial = $number * $?"
echo "Factorial of $1 is $?."
Also see Example A-15 for an example of recursion in a script. Be aware that recursion is resource-intensive and executes slowly, and is therefore generally not appropriate in a script.