|
||
23.2. Local VariablesWhat makes a variable "local"?
|
Local variables permit recursion, [1] but this practice generally involves much computational overhead and is definitely not recommended in a shell script. [2]
Example 23-13. Recursion, using a local variable
#!/bin/bash # factorial # --------- # Does bash permit recursion? # Well, yes, but... # It's so slow that you gotta have rocks in your head to try it. MAX_ARG=5 E_WRONG_ARGS=65 E_RANGE_ERR=66 if [ -z "1ドル" ] then echo "Usage: `basename 0ドル` number" exit $E_WRONG_ARGS fi if [ "1ドル" -gt $MAX_ARG ] then echo "Out of range (5 is maximum)." # Let's get real now. # If you want greater range than this, #+ rewrite it in a Real Programming Language. exit $E_RANGE_ERR fi fact () { local number=1ドル # Variable "number" must be declared as local, #+ otherwise this doesn't work. if [ "$number" -eq 0 ] then factorial=1 # Factorial of 0 = 1. else let "decrnum = number - 1" fact $decrnum # Recursive function call (the function calls itself). let "factorial = $number * $?" fi return $factorial } fact 1ドル echo "Factorial of 1ドル is $?." exit 0
See also Example A-16 for an example of recursion in a script. Be aware that recursion is resource-intensive and executes slowly, and is therefore generally not appropriate to use in a script.
Herbert Mayer defines recursion as ". . . expressing an algorithm by using a simpler version of that same algorithm . . ." A recursive function is one that calls itself.
Too many levels of recursion may crash a script with a segfault.
#!/bin/bash # Warning: Running this script could possibly lock up your system! # If you're lucky, it will segfault before using up all available memory. recursive_function () { echo "1ドル" # Makes the function do something, and hastens the segfault. (( 1ドル < 2ドル )) && recursive_function $(( 1ドル + 1 )) 2ドル; # As long as 1st parameter is less than 2nd, #+ increment 1st and recurse. } recursive_function 1 50000 # Recurse 50,000 levels! # Most likely segfaults (depending on stack size, set by ulimit -m). # Recursion this deep might cause even a C program to segfault, #+ by using up all the memory allotted to the stack. echo "This will probably not print." exit 0 # This script will not exit normally. # Thanks, St�phane Chazelas.