[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Passing variables by reference conflicts with local
From: |
Bill Gradwohl |
Subject: |
Re: Passing variables by reference conflicts with local |
Date: |
Thu, 26 Apr 2012 12:02:20 -0600 |
I added a bit if code to show some things that I did and did not expect.
#!/bin/bash
var=global
foo() {
echo
local var=foo
unset var
echo ${FUNCNAME[@]}: $var
displayVar
displayVarfoo() {
echo ${FUNCNAME[@]}: $var
}
displayVarfoo
}
bar_unset() {
unset var
echo ${FUNCNAME[@]}: $var
displayVar
displayVarbar_unset() {
echo ${FUNCNAME[@]}: $var
}
displayVarbar_unset
echo
newVar=bar_unset
}
bar() {
echo
local var=bar
bar_unset
echo ${FUNCNAME[@]}: $var $newVar
displayVar
displayVarbar() {
echo ${FUNCNAME[@]}: $var $newVar
}
displayVarbar
}
displayVar() {
echo ${FUNCNAME[@]}: $var $newVar
}
foo
bar
echo $var $newVar
Produces:
root@billlaptop ycc# ./zzz
foo main:
displayVar foo main:
displayVarfoo foo main:
bar_unset bar main: global
displayVar bar_unset bar main: global
displayVarbar_unset bar_unset bar main: global
bar main: global bar_unset
displayVar bar main: global bar_unset
displayVarbar bar main: global bar_unset
global bar_unset
With both internal and external display functions, I don't see a change in
their view of the world. That was expected as there's no such thing as a
nested or sub function from what I've been able to determine. All functions
live just below main and no matter how defined nested or not, they all end
up at the same level. Correct?
It appears that in foo, once the name is unset, any sub function in the
call chain can no longer see that name. So, if you want to make sure a sub
function can't touch a variable, put another function in between that
localises and then unsets the variable.
When newVar is created in bar_unset, it is created at the main level.
bar_unset is long gone and the variable it created lives on in Main. The
tail wagging the dog comes to mind.
If there's another interpretation than the one I came up with, please
correct me as much of this is guess work on my part.
--
Bill Gradwohl
Re: Passing variables by reference conflicts with local, Chet Ramey, 2012/04/28
Re: Passing variables by reference conflicts with local, Dan Douglas, 2012/04/30