Session and utilities
The local command
Declares variables that exist only inside a function and do not leak outside.
Most useful options
-Saves the shell options (set) and restores them when the function returns.-aCreates a local indexed array.-ACreates a local associative array.-iThe local variable is an integer: its value is evaluated as arithmetic.-rThe local variable becomes read-only during the function.-xExports the local variable to the environment of the programs the function runs.Copy-ready examples
$ printf 'saluda() {\nlocal x=1\necho hola\n}\nsaluda\n' > f.sh && bash f.shwrites a function with a local variable and runs it.Example output
hola
$ printf 'f() {\nlocal x=1\necho "dentro $x"\n}\nf\necho "fuera [$x]"\n' > f.sh && bash f.shthe variable exists inside the function and disappears when it returns.Example output
dentro 1 fuera []
$ printf 'f() {\nlocal -i n=2+3\necho $n\n}\nf\n' > g.sh && bash g.shwith -i, the value is calculated when it is assigned.Example output
5
$ printf 'f() {\nlocal -r K=9\nK=1\n}\nf\n' > h.sh && bash h.sha read-only local does not accept changes inside the function.Example output
bash: K: readonly variable
You can try them in the browser terminal: it does not touch your computer.
Common errors
| Message | Cause | Fix |
|---|---|---|
| bash: local: can only be used in a function | You used local outside a function. There is no local scope outside functions. | Remove local, or put the line inside a function. At the top level, use declare. |
| bash: local: -q: invalid option | local only accepts the declare options, and -q is not one of them. | Use a valid option such as -a, -A, -i, -r or -x. The help is available with help local. |
| bash: local: `1x=2': not a valid identifier | The name starts with a number, and variable names cannot do that. | Start the name with a letter or an underscore, for example _1x=2. |
Typical mistakes
- Outside a function, local is an error and creates nothing.
- If the function calls another one, the called function sees the caller's local variable: the scope is dynamic.
- local x=$(command) makes $? be 0 even when the command fails. Declare first and assign afterwards.
Differences from similar commands
FAQ
What if I want the variable visible outside the function?
Do not declare it local: use a global variable, or return the value with echo and capture it with $(...).
Does each call keep the value from the previous one?
No: each call creates its own copy, which disappears when the function ends.
Does it work with arrays?
Yes: local -a list=(a b) creates a local array that exists only inside the function.
Learn to actually use it
The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.
Start the free course