Scope of Local Variables in Shell Functions
73
votes
6
answers
91471
views
After reading [24.2. Local Variables](http://tldp.org/LDP/abs/html/localvar.html) , I thought that declaring a variable
var
with the keyword local
meant that var
's value was only accessible within the block of code delimited by the curly braces of a function.
However, after running the following example, I found out that var
can also be accessed, read and written from the functions invoked by that block of code -- i.e. even though var
is declared local
to outerFunc
, innerFunc
is still able to read it and alter its value.
[**Run It Online**](http://www.tutorialspoint.com/execute_bash_online.php?PID=0Bw_CjBb95KQMd1ptTmpoOWUyS3M)
#!/usr/bin/env bash
function innerFunc() {
var='new value'
echo "innerFunc: [var:${var}]"
}
function outerFunc() {
local var='initial value'
echo "outerFunc: before innerFunc: [var:${var}]"
innerFunc
echo "outerFunc: after innerFunc: [var:${var}]"
}
echo "global: before outerFunc: [var:${var}]"
outerFunc
echo "global: after outerFunc: [var:${var}]"
Output:
global: before outerFunc: [var:] # as expected, var
is not accessible outside of outerFunc
outerFunc: before innerFunc: [var:initial value]
innerFunc: [var:new value] # innerFunc
has access to var
??
outerFunc: after innerFunc: [var:new value] # the modification of var
by innerFunc
is visible to outerFunc
??
global: after outerFunc: [var:]
**Q: Is that a bug in my shell (bash 4.3.42, Ubuntu 16.04, 64bit) or is it the expected behavior ?**
**EDIT:** Solved. As noted by @MarkPlotnick, this is indeed the expected behavior.
Asked by maddouri
(831 rep)
May 11, 2016, 04:22 PM
Last activity: Oct 18, 2024, 07:07 PM
Last activity: Oct 18, 2024, 07:07 PM