What does `local` do, and what is dynamic scoping?
AdvancedConceptFunctions, exit codes, strict mode and traps
Answer
local limits a variable to the function and the functions it calls. Bash scoping is dynamic: a called function sees (and can modify) its caller's locals, not just globals.
n=100
counter() { n=$((n + 1)); }
retry() { local n=1; counter; echo "inside: $n"; } # counter changed retry's n
retry; echo "global: $n" # inside: 2 global: 100
This causes real bugs when a helper like retry declares local n and the retried function uses a global n. Prefix helper locals (_try, _rc) in shared libraries.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.BeginnerWhy can `((count++))` kill a script under `set -e`?Intermediate