Scope Variables With local in Bash

Keep function variables from clobbering the caller's environment.

macOSbashshellscriptingLow risk
Declare function variables with local inside the function body.

01Command

Command
$ count() { local n=0; n=$((n+1)); echo "$n"; }; count

02What it does

Without local, every assignment is global and one function can silently overwrite another's data. local keeps functions self-contained, which is essential as scripts grow; there is no GUI analogue because this is language-level scripting behaviour.

03Risk

RiskLow risk
RequirementsmacOS default zsh/bash (bash 3.2+; some features need bash 4+ via Homebrew)
CompatibilitymacOS with bash 3.2+ (GNU bash 4+ via Homebrew for advanced features)
!Warning: local is only valid inside a function; using it at top level is an error.

04Undo

✓No undo needed — this command does not change persistent state.

05Sources

Last verified: 2026-10-13 · Category: Developer