1
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?

3

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Well, I got it. Function g does not overide global x but assign for the outside one line variable x.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.