On Thu, Apr 26, 2012 at 12:02:20PM -0600, Bill Gradwohl wrote: > bar_unset() { > unset var > echo ${FUNCNAME[@]}: $var > displayVar > displayVarbar_unset() { > echo ${FUNCNAME[@]}: $var > } > displayVarbar_unset > echo > newVar=bar_unset > }
> 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. All variables are global unless declared local. Since you don't have newVar defined in any local scope, the final assignment in bar_unset creates it at the global scope. I don't see this as a surprise. It's how you return values from functions in bash. Pick a global variable (r, ret, whatever you want) and stuff the return value into that. You can even declare your "r" locally somewhere so that the value never propagates up higher than that point in the call chain. For example: # Return random number from 0 to ($1-1) in variable "r" rand() { local max=$((32768 / $1 * $1)); while (( (r=$RANDOM) >= max )); do :; done r=$((r % $1)) } foo() { local r rand 42 ... use $r ... } foo ... we don't see "r" here because it was scoped only within foo & its kids ...