On 4/23/12 4:56 AM, Clark Wang wrote: > When I revisit this 2 years old thread I don't understand why following > foo() function does not output the global var: > > $ cat foo.sh > var=global > foo() > { > local var=foo > unset var > echo foo: $var > } > bar_unset() > { > unset var > } > bar() > { > local var=bar > bar_unset > echo bar: $var > } > foo > bar > $ bash foo.sh > foo: > bar: global > $ > > In foo() it unsets its local var so why doesn't the subsequent $var refer > to the global var?
Greg's explanation in a subsequent message was pretty close. Back a number of years ago (16, to be exact), bash behaved like you expect. Between bash-1.14 and bash-2.0, I changed it in response to a number of bug reports that complained that a variable declared local in a function wasn't local when assigned a value in the function after being unset. Bash keeps a placeholder in the function's variable context so subsequent references to that unset variable don't traverse back through the call chain. This placeholder affects functions called by the function unsetting the local variable in the way you would expect dynamic scoping to work. This only affects the current function, though: an unset issued from farther down the call chain, as you discovered, will unset the local variable without creating a placeholder. Chet -- ``The lyf so short, the craft so long to lerne.'' - Chaucer ``Ars longa, vita brevis'' - Hippocrates Chet Ramey, ITS, CWRU c...@case.edu http://cnswww.cns.cwru.edu/~chet/