help-bash
[Top][All Lists]
Advanced

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

Re: name of a global variable to store the result of a function


From: Greg Wooledge
Subject: Re: name of a global variable to store the result of a function
Date: Tue, 26 May 2020 07:56:52 -0400
User-agent: Mutt/1.10.1 (2018-07-13)

On Sun, May 24, 2020 at 02:48:56PM -0400, Eli Schwartz wrote:
> eval "$varname=\"\$result\""
> 
> or do you use
> 
> printf -v "$varname" "%s" "$result"
> declare -g "$varname=$result"
> 
> How do you sanitize possible input values for $varname? printf/declare
> are fairly simple, just ensure there are no square brackets on the LHS.
> eval needs to protect against that, and also needs lots more sanitizing
> on top.

If you're going to validate the variable name, I'd prefer a whitelist
approach: make sure the name *only* contains :alnum: and underscore (in
the C locale), and doesn't begin with a digit.

Blacklisting specific syntax characters is typically wrong, because it's
easy to miss something.

Once that's done, there is nothing wrong with this particular use of eval.
This is one of the well-known, tried-and-true idioms for hacking around
the inability of functions to return values to their callers.  As long
as the content of $varname is eval-safe, all is well.

That said, my personal preference is still to use an agreed-upon variable
name to "return" the function's output value, such as "r" or "_r".  This
avoids all of the need to validate variable names, to triple-check an eval
usage, etc.  As long as you're not dealing with recursive functions, this
works quite well, in my experience.



reply via email to

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