local, Scope and the Finished Script
A local declaration creates a dynamically scoped variable for a Bash function invocation. Called functions can see it unless they declare a closer binding of the same name.
Limit working variables with local and inspect Bash's dynamic scoping behavior.
backup.sh has a count of archived folders. You add a helper function that uses a variable called count for something else, and suddenly the final report says "Archived 0 folders". Nothing warned you. In Bash, a function's variables leak by default.
The rule
Variables are global by default;
localkeeps them inside the function.
x=1
change() { x=2; }
protect() { local x=2; }
protect; echo "$x" # 1 the local x vanished when protect ended
change; echo "$x" # 2 change overwrote the global x- Any variable assigned in a function, without
local, is global: it changes or creates the script's variable. local name=valuecreates a variable that exists only while that function runs.- Bash scope is dynamic: a function called from another function can see the caller's locals. If
ahaslocal v=innerand callsb, thenbseesinner. - Local variables make recursion safe, because every call gets its own copy:
fact() {
local n=$1
if (( n <= 1 )); then echo 1
else echo $(( n * $(fact $(( n - 1 ))) )); fi
}
fact 4 # 24