Local Variables in Functions
A local variable is a variable that exists only while a function runs. It is created with the local command inside the function body, and it disappears when the function returns. Local variables let a function use names such as i, name or result for its own work without changing variables of the same name elsewhere in the script.
The need for local comes from a Bash rule that surprises people coming from other languages: variables in a function are global by default. Any variable a function assigns, without local, belongs to the whole script.
Variables Are Global Unless Declared Local
set_name() {
name="inside"
}
name="outside"
set_name
echo "name is now: $name"
Output:
name is now: inside
The function did not create its own name. It assigned to the script's name and overwrote outside. In a short script this may be harmless, but in a larger one a helper function can silently change a variable that some other part of the script depends on.
A variable that a function creates without local also stays after the function ends. Every new variable inside a function adds to the global namespace of the script.
Declaring a Local Variable
Put local in front of the assignment:
set_name2() {
local name="inside"
echo "in function: $name"
}
name="outside"
set_name2
echo "after call: $name"
in function: inside
after call: outside
While set_name2 runs, there are two variables called name: the global one, holding outside, and the local one, holding inside. Inside the function, the name refers to the local variable, which shadows (hides) the global one. When the function returns, the local variable is removed and the name refers to the global variable again, which was never changed.
A local variable that has no global partner simply disappears when the function ends:
make_temp() { local tmpval=42; }
make_temp
echo "tmpval=[${tmpval-unset}]"
tmpval=[unset]
The expansion ${tmpval-unset} (lesson 45) prints the word unset when the variable does not exist, which shows that tmpval is gone.
Syntax
local NAME
local NAME=VALUE
local NAME1=VALUE1 NAME2=VALUE2 NAME3
local [OPTIONS] NAME=VALUE
- One
localcommand can declare several variables, separated by spaces. - A name without
=VALUEis declared local but not set. - The options are the same as those of
declare:-i(integer),-a(indexed array),-A(associative array),-r(read-only),-x(exported) and-n(name reference, lesson 91). localworks only inside a function. At the top level of a script, it is an error:
t92.sh: line 79: local: can only be used in a function
The command returned status 1 and the script continued with the next line.
local Without a Value
In Bash, local x creates a new local variable that is unset, even when a global x exists:
x="global x"
f4() {
local x
echo "local x without value: [${x-unset}]"
x=changed
echo "inside: $x"
}
f4
echo "after: $x"
local x without value: [unset]
inside: changed
after: global x
Declaring a variable local first and assigning it later is common, for example to keep the exit status of a command substitution (lesson 90):
fail() { echo data; return 3; }
f11() {
local r=$(fail); echo "same line: $?"
local s
s=$(fail); echo "split: $?"
}
f11
same line: 0
split: 3
On the same line, $? is the status of local, which succeeded. With the declaration on its own line, the assignment s=$(fail) reports the status of fail.
To start a local variable with a copy of the global value, assign it explicitly. The right-hand side is expanded before the local variable is created, so it still sees the global value:
z=99
f() {
local z=$z
echo "local z=\$z gives: $z"
z=1
}
f
echo "global z: $z"
local z=$z gives: 99
global z: 99
The function works on its own copy and the global z keeps 99.
Loop Variables Need local Too
A for loop assigns its loop variable like any other assignment, so a loop inside a function changes a global variable unless the loop variable is declared local:
count_to() { for i in 1 2 3; do :; done; }
count_to2() { local i; for i in 1 2 3; do :; done; }
i="mine"; count_to; echo "i after count_to: $i"
i="mine"; count_to2; echo "i after count_to2: $i"
i after count_to: 3
i after count_to2: mine
count_to left the global i at 3, the last value of the loop (lesson 78). count_to2 declared i local first, so the loop used the local copy. This is easy to miss, because the loop variable is never written with an = sign. The same applies to variables set by read, by (( n++ )) and by printf -v.
Options: Integers, Arrays and Read-Only Locals
local accepts the same attributes as declare:
f6() {
local a=1 b=2 c
local -i n="5 + 5"
local -a arr=(x y z)
local -r fixed=10
echo "a=$a b=$b c=[${c-unset}] n=$n arr=${arr[*]} fixed=$fixed"
fixed=11
echo "status after assigning to fixed: $?"
}
f6
a=1 b=2 c=[unset] n=10 arr=x y z fixed=10
t92.sh: line 31: fixed: readonly variable
local -i n="5 + 5"evaluates the value as arithmetic, sonholds 10.local -a arr=(x y z)creates a local indexed array.local -r fixed=10creates a read-only local. The later assignmentfixed=11failed withreadonly variable. In this Bash 5.2.21 test, the rest of the function body was abandoned after that error (the lastechodid not run), which matches what lesson 40 showed for read-only variables in functions. The read-only local is still removed when the function returns, so it does not block the name for the rest of the script.
declare and its older synonym typeset also create local variables when used inside a function. To create or change a global variable from inside a function with declare, add -g:
f7() { declare d="declared"; typeset t="typeset"; }
f7g() { declare -g g="global via -g"; }
f7; echo "d=[${d-unset}] t=[${t-unset}]"
f7g; echo "g=$g"
d=[unset] t=[unset]
g=global via -g
Exporting a Local Variable to Child Processes
local -x creates a local variable that is also exported, so programs started by the function see it. When the function ends, the variable disappears along with its export:
f9() {
local -x MODE=debug
bash -c 'echo "child sees MODE=$MODE"'
}
f9
echo "after: MODE=[${MODE-unset}]"
bash -c 'echo "new child: MODE=[${MODE-unset}]"'
child sees MODE=debug
after: MODE=[unset]
new child: MODE=[unset]
This sets an environment variable for the commands of one function only, without affecting the rest of the script (environment variables were covered in lessons 36 to 38).
Local Variables and Recursion
Each call of a function gets its own set of local variables. This is what makes recursive functions, functions that call themselves, possible:
countdown() {
local n=$1
(( n == 0 )) && return
countdown $((n - 1))
echo "back in level n=$n"
}
countdown 3
back in level n=1
back in level n=2
back in level n=3
The call countdown 3 creates a local n holding 3 and calls countdown 2, which creates another local n holding 2, and so on down to 0. As each inner call returns, the local n of the level above becomes visible again with its own value, so the messages print 1, 2, 3. Without local, all levels would share one global n, and every message would show the value left by the deepest call.
A recursive function that computes a value combines local with the print-and-capture method of lesson 91:
fact() {
local n=$1
if (( n <= 1 )); then echo 1; return; fi
local sub
sub=$(fact $((n - 1)))
echo $(( n * sub ))
}
echo "5! = $(fact 5)"
5! = 120
unset on a Local Variable
unset removes the local variable. The global variable of the same name is not affected:
y="global y"
f10() {
local y="local y"
unset y
echo "after unset inside: [${y-unset}]"
}
f10
echo "outside: $y"
after unset inside: [unset]
outside: global y
When a Variable Should Stay Global
Not every variable in a function should be local. A function whose job is to update shared state, such as a counter or a setting read from the command line, must assign the global variable:
counter=0
next_id() { counter=$((counter + 1)); }
next_id; next_id; next_id
echo "counter=$counter"
counter=3
A clear way to work is to declare every variable that is only for the function's own use as local, and to leave global only the variables the function is meant to change. Giving those globals distinctive names (for example in capital letters, such as QUIET or TOTAL_ERRORS) makes it obvious at a glance which assignments reach outside the function. Lesson 94 uses this style for a complete script.
How Far a Local Variable Reaches
A local variable is not visible only in the function that declares it. Functions called by that function also see it, and can change it. This is called dynamic scoping, and it is the subject of lesson 93. For now, remember that local protects the caller's variables from the function, and that the function's locals are removed when it returns.
Portability
local is not part of the POSIX standard, but Dash and most other sh implementations support it. One difference matters. In Dash, local x without a value keeps the value of the outer variable, while Bash makes it unset:
x="global x"
g() { local x; echo "local x without value: [${x-unset}]"; x=changed; }
g; echo "after: $x"
Bash printed [unset]; Dash printed [global x]. Both restored the global value afterward. To get the same result in both shells, always give a local variable an explicit value, such as local x= or local x=$x. The local options -i, -a, -A, -r, -x and -n are Bash features (Dash rejected local -n in lesson 91).