Local Variables and Scope
Local Variables and Scope
In Bash, all variables are global by default—even when defined inside a function. Always use local to prevent state contamination:
counter=100
my_function() {
local counter=1 # Scoped exclusively to this function and its callees
echo "Inside: $counter"
}
my_function
echo "Outside: $counter" # 100 (Unchanged)Dynamic Scoping Warning: Bash uses dynamic scoping, not lexical scoping. A local variable declared in function A is visible to function B if A calls B!