bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: NOT changing global variables


From: Andrew Stitt
Subject: Re: NOT changing global variables
Date: Fri, 29 Dec 2006 16:38:22 -0800
User-agent: Mutt/1.4.2.1i

On Fri, Dec 29, 2006 at 11:43:14PM +0100, Frans de Boer wrote:
> Yes, I did expected such an answer of using a subshell, and yes I can
> get the return value, but I don need it. I need the output fed into
> another (maybe local) variable. I was under the impression that BASH was
> modeled after 'C', so I started using the functions as such. My mistake.
> I have the confirmation that it's not so strait forward as I expected.
> Never mind, I now know better, so thanks for the comment anyway.

One technique I use instead of output capturing is to use a variable
"reference". In the function allow the caller to specify a variable _name_
as a parameter. Then use eval to store the results in that variable
instead of sending it to stdout. This is similar to tcl's "upvar".

function foo() {
  local data=<do something>
  eval $1=\$data
}

a=1
echo $a
foo a
echo $a

If you didn't actually need a subshell to begin with then this eliminates
it. Removing extra subshells can help speed up your program, if thats
somethig that matters to you (it does to me, fwiw). Or if nothing else,
you limit the subshell's scope.

Goes without saying, that you should pick a naming convention for
variable names you intend to pass. Otherwise local function variables
may collide. "data" in place of "a" would be a bad choice in the above
example :-)

There may also be technical limitations to using eval like this. If
there are, Im eager to hear them.

-Andrew





reply via email to

[Prev in Thread] Current Thread [Next in Thread]