Local variables and dynamic scope
Use local name=value inside a function to create a variable belonging to that invocation. Bash uses dynamic scope: a function called by another function can see the caller’s local variables unless it declares its own local with the same name. Assigning to an existing visible variable without declaring a local may modify the caller’s variable. After a function returns, its locals disappear and outer values become visible again. declare inside a function normally creates a local unless -g is used. Use local -r for an invocation-local readonly value; attempting to reassign it fails. Prefer explicit arguments and deliberate output contracts rather than relying on a caller’s variable names. Dynamic scope is not lexical scope; the invocation chain, not the location of the function definition, matters. An inner function that declares its own local variable of the same name shadows the caller binding. A subshell can see inherited local values but cannot mutate the parent shell binding. These examples assume ordinary non-readonly outer bindings.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Shadow a global
name=globalshow() { local name=local; printf '%s\n' "$name"; }showprintf '%s\n' "$name"Expected stdout:
localglobalThe local shadows the global only while show runs.
Observe dynamic scope
label=globalinner() { printf 'seen=%s\n' "$label"; label=changed; }outer() { local label=outer inner printf 'outer=%s\n' "$label"}outerprintf 'global=%s\n' "$label"Expected stdout:
seen=outerouter=changedglobal=globalInner reads and modifies the nearest visible binding.
Protect local values
mode=globalinspect() { local -r mode=fixed declare scratch=temporary printf '%s:%s\n' "$mode" "$scratch"}inspectprintf '%s:%s\n' "$mode" "${scratch-unset}"Expected stdout:
fixed:temporaryglobal:unsetReadonly local mode and declare-created scratch disappear on return.
Common mistakes
Local does not mean invisible to called functions. Avoid relying on dynamically visible state unless that dependency is intentional and documented.
Practice
Create outer and inner functions that both use a variable named label. First omit local in inner, then add it. Predict the outer and global values after each call.
Next: Source files and reusable modules