On Mon, Oct 19, 2015 at 12:49:25PM -0700, Linda Walsh wrote: ... > I observe similar inconsistencies and confusion around > the use of 'dynamic vars' -- not really being global, not really > being local, but supposedly on some dynamic frame, "somewhere", > but not anywhere they've been declared or used.
Understanding dynamic (as opposed to static) variables is pretty key to understanding how bash works, but the manual doesn't seem to even address the issue, other than perhaps this line in the section about 'local': When local is used within a function, it causes the variable name to have a visible scope restricted to that function and its children. The children referred to are functions called from the function, but which are otherwise in the global namespace, so that a child of one function might be separately a child of a different function. I kind of like the way it works, but it's probably confusing if one is more used to (or thinking of) static variable scoping, which is much more common in many languages. I find it convenient to declare most variables using local, to the extent of putting the main code in an explicit (and somewhat redundant) main() function, called by main "$@" at the end of the script. Here's an example utility function (to split stuff into an array) that relies on the calling functions to declare the array variable V: split() { local IFS=$1; shift; V=($*); } # SEP ARGS... foo() { local -a V split , "some,comma,separated,words" printf "%s\n" "${V[@]}" ... } bar() { local -a V split ' ' "some space separated words" ... } baz() { split : "some:colon:separated:words" ... } The V seen by split() (but alas, not declared within it) is a distinct variable for foo() and bar(). baz() would cause a global V to be defined implicitly (from within split()), which I'd tend to avoid. Ken