/ Linux Reviews / Beginners: Learn Linux / Advanced Bash-Scripting Guide - en
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
# Global and local variables inside a function.
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"
# Now, to see if local variable "loc_var" exists outside function.
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.
# 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
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.
echo "global_var = $global_var" # global_var = 37
# Has been set by function call.
23.2.1. Local variables help make recursion possible.
Local variables permit recursion,
but this practice generally involves much computational
overhead and is definitely not
recommended in a shell script.
Example 23-13. 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 (5 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 $?."
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.
/ Linux Reviews / Beginners: Learn Linux / Advanced Bash-Scripting Guide
Meet new people