Here's the code.

var_change() {
 local var1='local 1'
 echo Inside function: var1 is $var1 : var2 is $var2
 var1='changed again'
 var2='2 changed again'


var1='global 1'
var2='global 2'
echo Before function call: var1 is $var1 : var2 is $var2
echo After function call: var1 is $var1 : var2 is $var2

And here's the output when executing the above script.

Before function call: var1 is global 1 : var2 is global 2
Inside function: var1 is local 1 : var2 is global 2
After function call: var1 is global 1 : var2 is 2 changed again

Just take a look at the final line which is After function call. I don't understand why var2 here is "2 changed again". I just thought that outside of the function var_change, the var2 variable must be global2.


In the function, var2 is not declared local, and therefore it is "global", which means that the value it has at the end of the function will be the value it has after the call of the function.

Said differently, the variable var1 within the function is "local" and therefore it is not the same variable as the global one of the same name, whereas this is not the case for var2.

  • Ah i got it! Seems like i was wrong about the executing order in the script. – The One Apr 12 '16 at 1:41


local var2='local 2'

to the function should change that.

  • 1
    This doesn't really answer the question. The script is clearly intended as a demonstration script, to learn how scoped variables work in bash. Changing the scope of the variables so they're all the same won't help the Original Poster learn what he is trying to learn. – Wildcard Apr 12 '16 at 3:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.