Function Scope and Variable Visibility
The scope of a variable is the part of a program in which its name can be seen and used. In Bash, scope decides which variable a name refers to when a script has a global variable, a local variable in one function, and perhaps another local variable of the same name in a function further up the chain of calls. Visibility is the related question of which pieces of code, and which other processes, can see a variable at all.
Lesson 92 introduced local. This lesson explains the exact rules Bash uses to look up a name, which differ from the rules of languages such as Python, C or JavaScript, and shows the other boundaries that limit visibility: subshells and child processes.
The Three Places a Variable Can Live
When a script runs, a variable can be:
- Global: created at the top level of the script, or inside a function without
local. It is visible everywhere in the current shell process. - Local: created with
local(ordeclarewithout-g) inside a function. It exists only while that function is running. - Exported: a global or local variable marked with
export(orlocal -x). It is also copied into the environment of programs that the shell starts.
The first two describe visibility inside the shell. The third describes visibility outside it.
Bash Uses Dynamic Scoping
Most modern languages use lexical scoping: a function sees the variables of the place where it was written. Bash uses dynamic scoping: a function sees the variables of the place where it was called. When a function uses a name, Bash looks for it in this order:
- The local variables of the function that is running.
- The local variables of the function that called it.
- The local variables of that function's caller, and so on up the chain.
- Finally, the global variables.
The first match wins. An example makes the rule visible:
show_color() {
echo "show_color sees: $color"
}
paint() {
local color="red"
show_color
}
color="blue"
paint
show_color
Output:
show_color sees: red
show_color sees: blue
show_color has no variable of its own called color. When it is called from paint, the lookup finds the local color of paint (step 2) before the global one, so it prints red. When it is called from the top level, there is no calling function, and the lookup reaches the global color, so it prints blue. The same function printed different values only because it was called from different places. In a lexically scoped language, show_color would print blue both times.
Called Functions Can Change the Caller's Locals
Dynamic scoping applies to assignments too. A function that assigns a name without local changes the first variable the lookup finds, and that may be a local variable of its caller:
inner() {
level="changed by inner"
}
outer() {
local level="outer's own"
inner
echo "outer now has: $level"
}
level="global"
outer
echo "global level: $level"
outer now has: changed by inner
global level: global
inner meant to set something called level. The lookup found the local level of outer first, so that is the variable that changed. The global level was untouched, because the local variable of outer was in the way. When outer returned, its local level was removed with the change still inside it.
Following a Chain of Calls
The lookup always uses the current chain of calls, so the same function can see different variables at different moments:
c() { echo "c sees v=$v"; }
b() { local v="from b"; c; }
a() { local v="from a"; b; c; }
v="global"
a
c sees v=from b
c sees v=from a
The chain for the first call of c is a → b → c. The nearest local v is in b. The chain for the second call is a → c, because b has already returned and its local v is gone. The nearest local v is now the one in a.
Bash keeps the current chain in the FUNCNAME array, which can help when you are trying to understand which variables a function can see:
lvl3() { echo "call stack: ${FUNCNAME[*]}"; }
lvl2() { lvl3; }
lvl1() { lvl2; }
lvl1
call stack: lvl3 lvl2 lvl1 main
The first element is the running function and each later element is its caller. main stands for the top level of the script.
When Dynamic Scoping Causes a Clash
Dynamic scoping becomes a problem when a helper function uses a global variable to hand back a result (lesson 91), and a caller happens to have a local variable with the same name:
get_max() {
result=$1
for n in "$@"; do (( n > result )) && result=$n; done
}
report() {
local result="report text"
get_max 4 9 2
echo "report's result is now: $result"
}
report
echo "global result: [${result-unset}]"
report's result is now: 9
global result: [unset]
get_max was written to set a global result. Called from report, it overwrote the local result of report instead, and no global result was ever created. Nothing in get_max itself is wrong; the clash only appears because of where it was called from.
There are several ways to avoid this:
- Print the result and let the caller capture it with
$( )(lesson 91). The function then sets no shared names. - Let the caller choose the variable name, with
printf -vorlocal -n(lesson 91). - Give the shared variable a name that is unlikely to be used elsewhere, such as
GET_MAX_RESULT. - Declare the helper's own working variables local. In
get_max, the loop variablenshould also belocal n, for the same reason.
Writing a Global Variable from Inside a Function
declare -g assigns the global variable directly, skipping any local variables found along the chain:
setter() {
declare -g mode="set with -g"
echo "inside setter, mode=$mode"
}
user() {
local mode="user's local"
setter
echo "user sees: $mode"
}
mode="original"
user
echo "global mode: $mode"
inside setter, mode=user's local
user sees: user's local
global mode: set with -g
The global mode changed, but inside setter and user the name mode still referred to the local variable of user, because that local variable shadows the global one until user returns. Use declare -g when a function must set a global value no matter where it is called from, and keep in mind that the new value only becomes visible once the shadowing local variables are gone.
Listing the Variables a Function Declared
local with the -p option, used inside a function, prints the local variables of that function:
inspect() {
local a=1 b=two
local -p
}
inspect
declare -- a="1"
declare -- b="two"
declare -p NAME prints a single variable with its attributes, which is useful while debugging scope problems.
unset and Dynamic Scoping
unset follows the same lookup. If a function unsets a name that is local in its caller, it removes the caller's local variable, and the name then refers to the next variable in the chain:
g=global
callee() {
unset g
echo "callee after unset: [${g-unset}]"
}
caller() {
local g=local
callee
echo "caller after callee: [${g-unset}]"
}
caller
echo "top: [${g-unset}]"
callee after unset: [global]
caller after callee: [global]
top: [global]
In this Bash 5.2.21 run, unset g in callee removed the local g of caller, so both functions saw the global value afterward, and the global g survived. This behavior is rarely what a script needs; it is one more reason to avoid touching names a function did not create.
Functions Themselves Are Always Global
Variables can be local, but function definitions cannot. A function defined inside another function becomes available to the whole script once the outer function has run:
define_helper() {
helper() { echo "helper runs"; }
}
type helper >/dev/null 2>&1 && echo "helper exists" || echo "helper does not exist yet"
define_helper
helper
helper does not exist yet
helper runs
The inner definition is just a command that runs when define_helper runs. Until then, helper does not exist; afterwards, it exists everywhere, including outside define_helper.
Subshells Are a Hard Boundary
Everything above concerns one shell process. A subshell is a copy of the shell. It starts with copies of all variables, local and global, but any change it makes stays in the copy:
total=0
add_in_sub() { ( total=100 ); }
add_in_sub
echo "after ( ): $total"
printf '1\n2\n3\n' | while read -r n; do total=$((total + n)); done
echo "after pipe: $total"
while read -r n; do total=$((total + n)); done < <(printf '1\n2\n3\n')
echo "after process substitution: $total"
sub_fn() ( total=500; echo "inside: $total" )
sub_fn
echo "after subshell function: $total"
after ( ): 0
after pipe: 0
after process substitution: 6
inside: 500
after subshell function: 6
- Parentheses
( )run their commands in a subshell, sototal=100was lost. - The loop on the right side of a pipe also runs in a subshell (lesson 61), so the sum was lost.
- With process substitution,
< <( ), the loop runs in the current shell and the sum of 6 is kept. - A function whose body is written with parentheses instead of braces,
sub_fn() ( ... ), always runs in a subshell. Nothing it assigns can reach the caller, which makes such a function safe to use for code that changes directories or settings temporarily.
Command substitution, $( ), is also a subshell, as lesson 91 showed. Dynamic scoping never crosses this boundary: a subshell can read the variables it inherited, but it cannot change the originals.
Visibility to Other Programs
A program started by the script, such as another Bash script, python3 or env, runs in a separate process. It does not see shell variables at all unless they are exported:
greeting="hello"
bash -c 'echo "child sees greeting=[$greeting]"'
export greeting
bash -c 'echo "after export: [$greeting]"'
child sees greeting=[]
after export: [hello]
Exporting copies the value into the child's environment. The child receives a copy, so a change made in the child never comes back to the script. local -x (lesson 92) limits an exported variable to the commands of one function.
Changing the Behavior of local with Shell Options
Bash has shell options that adjust how local interacts with outer variables. With shopt -s localvar_inherit (Bash 5.0 or later), a new local variable starts with the value of the variable it shadows instead of being unset:
shopt -s localvar_inherit
w="global w"
f() { local w; echo "with localvar_inherit: [$w]"; }
f
shopt -u localvar_inherit
with localvar_inherit: [global w]
Such options change the meaning of every local in the script, so it is usually clearer to write local w=$w where a copy is wanted (lesson 92). shopt is covered in lesson 149.
Reasoning About Scope in a Script
When a variable has an unexpected value inside a function, ask these questions in order:
- Did this function declare the name with
local? If so, the function's own value is used. - If not, which functions are on the call chain right now (
FUNCNAME), and does any of them have a local variable with this name? The nearest one is used and changed. - If none does, the global variable is used and changed.
- Is this code running in a subshell (
( ),$( ), a pipeline, or a function with a parenthesized body)? If so, changes will not survive. - Is the value needed by another program? Then it must be exported.
Keeping each function's working variables local, and passing values in through arguments (lesson 89) and out through output or status (lessons 90 and 91), means the answer to these questions is almost always the first one.
Portability
Dynamic scoping of local variables also applies in Dash, which shares the same lookup rule for functions that call each other. The differences are in the details: Dash keeps the outer value for local x (lesson 92), and declare, declare -g, local -p, local -n, FUNCNAME, shopt and process substitution are Bash features. POSIX itself does not define local at all, so in strictly portable scripts every function variable is global (lessons 188 and 189).