help-bash
[Top][All Lists]
Advanced

[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: Marco Ippolito
Subject: Re: [Help-bash] taking the name of a variable from another variable
Date: Wed, 4 Jul 2018 03:09:04 +0200
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.8.0

On 04/07/18 02:29, Robert Durkacz wrote:

> On Tue, Jul 03, 2018, Greg Wooledge wrote:
>> A script CAN'T set an environment variable.  Once the script exits, that
> variable will be gone.
>
> Yes, I know. I wrote 'shell script' but meant to write 'shell function'.
> The next reply in the thread, from João Eiras, answered the question.

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?"):

Before:

$ bash -c 'echo "$foo"'
<blank line>

Defining a function to set, and thus export, an environment variable 
(parameters such as name=value aren't exported by default, envvars are):

$ setenv() { local -n varname=$1; local -r value=$2; export varname=$value; }

Using said function:

$ setenv foo $'Hello,\nworld!'

After:

$ bash -c 'echo "$foo"'
Hello,
world!

You did not specify which $BASH_VERSION you are on, so Greg offered this link:

https://mywiki.wooledge.org/BashFAQ/006

which does hint to how things change when you can use Namerefs:

>  Most of this page was written prior to Bash 4.3. Namerefs 
> (typeset/declare/local -n) may significantly change the considerations for 
> indirection.
(Source: the linked FAQ)

Jõao's formulation works with versions prior to 4.3, but you might like the 
cleaner syntax of Namerefs better if you have the choice, modulo personal 
preference and portability/compatibility concerns.




reply via email to

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