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?

kingkong
  • 119
  • 8
  • 2
    see https://stackoverflow.com/questions/48165818/understanding-lexical-scoping-is-wikipedia-correct and https://stackoverflow.com/questions/13998075/setting-environment-variable-for-one-program-call-in-bash-using-env – pynexj Jul 12 '22 at 04:51
  • While we are on the topic, do also check the [`local`](https://tldp.org/LDP/abs/html/localvar.html) keyword. – anishsane Jul 12 '22 at 06:25
  • `function h() { local x=3; echo $x; } x=2 h` This output is 3.So I can say the order is LEG: local -> environ -> global? – kingkong Jul 12 '22 at 06:48

1 Answers1

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.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • Well, I got it. Function g does not overide global x but assign for the outside one line variable x. – kingkong Jul 12 '22 at 06:21