Skip to the workspace
Pebellslearn by building
Loops and Functions  ›  Capstone Project

local, Scope and the Finished Script

Function Scopes 15 minA 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.

shell bash / local, Scope and the Finished Script

Explore each scene at your own pace.

01 · The rule

The rule

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; local keeps 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=value creates 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 a has local v=inner and calls b, then b sees inner.
  • 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
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.