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.

Caution

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 make recursion possible.

Local variables permit recursion, [1] but this practice generally involves much computational overhead and is definitely not recommended in a shell script. [2]

See also Example A-14 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.

Notes

[1]

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.

[2]

Too many levels of recursion may crash a script with a segfault.
#!/bin/bash

recursive_function ()		   
{
(( $1 < $2 )) && f $(( $1 + 1 )) $2;
#  As long as 1st parameter is less than 2nd,
#+ increment 1st and recurse.
}

recursive_function 1 50000  # Recurse 50,000 levels!
# Segfaults, of course.

#  Recursion this deep might cause even a C program to segfault,
#+ by using up all the memory allotted to the stack.

# Thanks, S.C.

exit 0  # This script will not exit normally.