🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Function Scope

Function scope decides which parts of a script can see a variable. By default a function's variables are global, and a called function can see its caller's locals.

Without local, the change leaks out

The function assigns a new name with no local keyword. The new value is still there after the call ends.

name="Ada"
rename() {
  name="Grace"
}
rename
echo "name: $name"

local keeps the change inside

The function uses local for its own copy of the name. The outside value stays Ada after the call.

name="Ada"
rename() {
  local name="Grace"
  echo "inside: $name"
}
rename
echo "outside: $name"

A called function sees its caller's locals

The show function never sets label itself. It still prints the label from wrap, because wrap called it.

show() {
  echo "seen: $label"
}
wrap() {
  local label="from caller"
  show
}
wrap

Example

total=10
add_step() {
  total=$(( total + step ))
}
run() {
  local step=3
  add_step
  echo "total: $total"
}
run
echo "final: $total"

Key points

  • local: marks a variable as local to the function it appears in.
  • Global pitfall: an assignment without local changes the variable everywhere, even after the call ends.
  • Dynamic scope: a function sees the locals of the function that called it.
  • local inside a function: keeps a helper name from leaking into the rest of the script.
  • Use local for: scratch values a function needs only while it runs.

In this example, run sets a local step of 3 and calls add_step. The helper add_step has no step of its own, yet it reads run's local step. It adds 3 to the global total, so both printed lines show 13.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A function assigns a variable without local. What happens to the caller's value after the call?