[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] taking the name of a variable from another variable
From: |
Greg Wooledge |
Subject: |
Re: [Help-bash] taking the name of a variable from another variable |
Date: |
Thu, 5 Jul 2018 08:16:25 -0400 |
User-agent: |
NeoMutt/20170113 (1.7.2) |
On Wed, Jul 04, 2018 at 03:09:04AM +0200, Marco Ippolito wrote:
> On 04/07/18 02:29, Robert Durkacz wrote:
> > Yes, I know. I wrote 'shell script' but meant to write 'shell function'.
>
> With the original intent now disambiguated, may I submit this for your
> consideration, to illustrate how the nameref attribute of a variable may also
> help in answering a question you embed in the original post (i.e. "can I
> obtain the name of a variable from another variable?"):
> $ setenv() { local -n varname=$1; local -r value=$2; export varname=$value; }
Be careful with bash name refs. There's a potential namespace collision
between the variable name provided by the caller, and the local variables
of the function. With name refs in play, they all mingle in a single
namespace.
And it's NOT just the variable name that the ref points to, either. ALL
the local variables of the function are now in play and can wreak havoc:
wooledg:~$ setenv() { local -n varname=$1; local -r value=$2; export
varname=$value; }
wooledg:~$ setenv value 42
bash: value: readonly variable
The nameref points to the name "value", so export tries to set the
value of "value", but you've made that readonly, so it can't, and
thus the error. The collision between the caller's variables and the
function's local variables is very real, and very hard to deal with.
The best approach seems to be putting something like _myfuncname_ (with
literal underscores) in front of ALL of the function's local variables
when name refs are in play.