23.2. Local Variables

What makes a variable local?

local variables

A variable declared as local is one that is visible only within the block of code in which it appears. It has local "scope." In a function, a local variable has meaning only within that function block.

Example 23-12. Local variable visibility

#!/bin/bash # Global and local variables inside a function. func () { local loc_var=23 # Declared as local variable. echo # Uses the 'local' builtin. echo "\"loc_var\" in function = $loc_var" global_var=999 # Not declared as local. # Defaults to global. echo "\"global_var\" in function = $global_var" } func # Now, to see if local variable "loc_var" exists outside function. echo echo "\"loc_var\" outside function = $loc_var" # $loc_var outside function = # No, $loc_var not visible globally. echo "\"global_var\" outside function = $global_var" # $global_var outside function = 999 # $global_var is visible globally. echo exit 0 # In contrast to C, a Bash variable declared inside a function #+ is local *only* if declared as such.


Before a function is called, all variables declared within the function are invisible outside the body of the function, not just those explicitly declared as local.
#!/bin/bash func () { global_var=37 # Visible only within the function block #+ before the function has been called. } # END OF FUNCTION echo "global_var = $global_var" # global_var = # Function "func" has not yet been called, #+ so $global_var is not visible here. func echo "global_var = $global_var" # global_var = 37 # Has been set by function call.

23.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. [5]

Example 23-14. 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 aboutauthor.html aliases.html arithexp.html arrays.html asciitable.html assortedtips.html authorsnote.html awk.html bash2.html bash-options.html bashver2.html bashver3.html basic.html biblio.html colorizing.html command-line-options.html commandsub.html communications.html comparison-ops.html complexfunct.html contributed-scripts.html copyright.html credits.html dblparens.html debugging.html declareref.html devproc.html devref1.html disclaimer.html dosbatch.html endnotes.html escapingsection.html exercises.html exitcodes.html exit-status.html external.html extmisc.html filearchiv.html files.html fto.html functions.html globbingref.html gotchas.html here-docs.html histcommands.html index.html intandnonint.html internal.html internalvariables.html invoking.html io-redirection.html ioredirintro.html ivr.html list-cons.html localization.html localvar.html loopcontrol.html loops1.html loops.html mathc.html mirrorsites.html miscellany.html moreadv.html nestedifthen.html nestedloops.html numerical-constants.html operations.html opprecedence.html ops.html optimizations.html options.html othertypesv.html parameter-substitution.html part1.html part2.html part3.html part4.html part5.html portabilityissues.html prelimexer.html process-sub.html procref1.html quoting.html quotingvar.html randomvar.html recess-time.html recurnolocvar.html recursionsct.html redirapps.html redircb.html refcards.html regexp.html restricted-sh.html revisionhistory.html sample-bashrc.html scriptanalysis.html scrstyle.html securityissues.html sedawk.html sha-bang.html special-chars.html standard-options.html string-manipulation.html subshells.html sysscripts.html systemdirs.html system.html terminalccmds.html testbranch.html testconstructs.html testsandcomparisons.html tests.html testtest.html textproc.html timedate.html todolist.html toolsused.html unofficialst.html untyped.html varassignment.html variables2.html variables.html varsubn.html wherehelp.html why-shell.html winscript.html wrapper.html writingscripts.html x16044.html x16712.html x16834.html x21467.html x8885.html xrefindex.html zeros.html $?" fi return $factorial } fact $1 echo "Factorial of $1 is $?." exit 0

Also see 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 in a script.



Otherwise known as redundancy.


Otherwise known as tautology.


Otherwise known as a metaphor.


Otherwise known as a recursive function.


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.