Reputation: 261
Say I have the following code:
# Global variable x
x="Hi"
foo()
{
# Local variable x
local x="Hello"
}
Can I access (read and set) the global variable x
from inside the function foo()
?
Upvotes: 6
Views: 2974
Reputation: 390
Actually, by using a nested function, this can be done.
foo()
{
local nested_ret
foo_nested(){
local x
x="Hello"
nested_ret="$x"
}
foo_nested "$@"
x="$nested_ret"
}
x="Hi"
foo
echo "x is $x"
Output: x is Hello
Upvotes: 0
Reputation: 48884
Once you have shadowed the global variable with a local of the same name there is no way to access the global anymore. Search for "shadow" in the manual.
As mentioned you can access the global variable before declaring the local, but if that isn't what you need (e.g. if you want to write back to the global variable after declaring the local) the only option is to use a different name. It's fairly common to use a _
or __
prefix to denote special or private variables that should not be set at the global scope. That way all (well-behaved) callers will not collide with your variable name.
Upvotes: 2
Reputation: 96016
Try the following:
1 x="Hi"
2
3 foo()
4 {
5 echo $x
6 x="Hello"
7 echo $x
8 local x="Bye"
9 echo $x
10 }
11
12 foo
13 echo $x
This will print:
Hi
Hello
Bye
Hello
echo $x
prints the value of the global x
foo
, local x
value wasn't changedUpvotes: 0