LinuxCommandLibrary

local

TLDR

Declare local variable

$ local [varname]
copy
Declare with initial value
$ local [varname]="[value]"
copy
Declare integer variable
$ local -i [count]=0
copy
Declare array
$ local -a [array]=([a] [b] [c])
copy
Declare readonly local
$ local -r [constant]="[value]"
copy

SYNOPSIS

local [option] name[=value] ...

DESCRIPTION

local is a bash builtin that declares variables with local scope within a function. Local variables are not visible outside the function where they are declared.
Using local prevents function variables from polluting or conflicting with the global namespace.

PARAMETERS

-a

Declare as indexed array.
-A
Declare as associative array.
-i
Declare as integer.
-l
Convert to lowercase.
-u
Convert to uppercase.
-r
Make readonly.
-n
Name reference.

EXAMPLE

$ my_function() {
    local result="success"
    local -i count=5
    echo "$result: $count"
}
# $result and $count not accessible here
copy

CAVEATS

Only valid inside functions. Not POSIX-compliant (use typeset for portability). Local variables shadow global ones. Subshells inherit but cannot modify.

SEE ALSO

declare(1), typeset(1), export(1), readonly(1)

Copied to clipboard