variables

local

Declares a variable scoped to the current function, hiding any global of the same name during the function's execution. Accepts the same attribute flags as declare (-a, -A, -i, -r, -n, ...).

local [OPTION] NAME[=VALUE] ...

Common flags / operators

Flag / Operator Purpose
-a / -A Local indexed/associative array
-i Local integer variable
-r Local readonly (constant within function)
-n Nameref — reference another variable by name (bash 4.3+)

Examples

fn() { local x=1; echo "$x"; }

x exists only inside fn; the outer x is unaffected.

fn() { local -a items=(a b c); }

Local array — cleaned up when fn returns.

fn() { local -n ref=$1; ref=hello; }; fn myvar

Nameref — assigns to whichever var is named in $1.

fn() { local IFS=,; parts=($1); }

Local IFS restores the original when fn returns.

Gotcha

'local x=$(cmd)' MASKS the exit status of cmd — always shows 0. Declare-and-assign separately if you need the status: 'local x; x=$(cmd) || return'.

Related

← All Bash builtins · Linux commands