Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps