x=1
function f()
{
echo $x
}
x=2 f #2
function g()
{
x=3
a=4
echo $x
}
a=5
x=2 g #3
echo $x #1
echo $a #4
Why the output is 2 3 1 4 ? Why function f access the one line variable x rather than the global one? Why function g create global variables x and a, but the x does not override outside global one?
Why function f access the one line variable x rather than the global one?
Because specifying a variable as part of a command sets it in the dynamic scope of the execution of that command (only).
Why function g create global variables x and a, but the x does not override outside global one?
g
assigns to variables x
and a
. But in the context of the call x
is effectively local to it, on account of a value having been specified for that variable as part of the call. The same is not true of a
, so the assignment to it affects the shell environment normally.