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
declare / typeset / readonly
Declares variables with attributes: arrays, associative arrays, integers, readonly, lowercase/uppercase, exported. 'readonly' is a shortcut for 'declare -r' that locks a variable so it cannot be reassigned or unset for the lifetime of the shell.
return
Exits a shell function or sourced script and returns exit status N (0-255). Without N, returns the exit status of the last command executed in the function.
export
Marks a shell variable (or function with -f) for export to the environment of subsequently executed commands. Without arguments, prints all exported variables in a re-importable format.
unset
Removes a variable or function from the shell — different from setting it to empty. Without a flag it targets variables first, then functions, unless -f or -v is specified.
shift
Renames positional parameters: $2 becomes $1, $3 becomes $2, and so on, decrementing $#. Optional N shifts by N positions and is common in manual argument parsing loops.