As Chet said, use internal variables that are unlikely to conflict. # Param: $1 variable name to return value to blackbox() { local __bb_a # internal: __, blackbox: bb, a: _a eval $1=bar }
f() { local a blackbox a echo $a } f # no conflict I prefer to avoid using eval by using declare, but declare inside a function makes the variable local. Wouldn't it be nice to have a global flag (declare -g) like zsh's typeset -g. d='ls /;true' # aren't you glad it's not "rm -rf" instead of "ls" f "$d" # oops So in the mean time, you should sanitize those evals. On Sat, May 1, 2010 at 3:18 AM, Freddy Vulto <fvu...@gmail.com> wrote: > On 100430 08:19, Greg Wooledge wrote: >> On Fri, Apr 30, 2010 at 12:02:58AM +0200, Freddy Vulto wrote: >> > Passing variables by reference however, has a caveat in that >> > local variables override the passing by reference, e.g.: >> > >> > t() { >> > local a >> > eval $1=b >> > } >> > unset a; t a; echo $a # Outputs nothing, expected "b" >> >> Why did you declare 'a' to be local if that's not what you wanted? >> Why did you expect 'b' to be output, if you used a local variable? > > t() is an example library function which - as a black box - can contain > many local variables. Local 'a' is just an example. > > I would like to call t(), and let it return me a filled variable by > reference, that is without polluting the global environment. > > Problem is, all variables work except 'a' because t() happens to declare > this local - which I'm not supposed to know because t() is a black box. > > Maybe the example is not clear because 'a' becomes global after all, > and is this a better example: > > # Param: $1 variable name to return value to > blackbox() { > local a > eval $1=bar > } > > This goes all right: > > f() { > local b > blackbox b > echo $b > } > f # Echos "bar" all right > > But if I change 'b' to 'a', this conflicts with blackbox() local 'a': > > f() { > local a > blackbox a > echo $a > } > f # Outputs nothing unexpected > > > Freddy Vulto > http://fvue.nl/wiki/Bash:_passing_variables_by_reference > > >