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: Tue, 3 Jul 2018 16:21:55 +0200
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.8.0

In short, follow Greg's advice.

If this is an interview question (I got it once), the answer is "if you
mean setting a variable in the _current_ shell's environment, a child
process won't normally be able to do that, modifying its own environment
instead". Demonstrates some understanding of the separation between
parent and child processes.

You could, against my advice, add: "... unless that child process were
something akin to a debugger and we had access to elevated privileges,
attaching back to the launching shell and doing something like: sudo gdb
-p "$1" -batch -ex 'p setenv("baz", "quux")' -ex quit. (You would pass
the parent shell's PID, $$, into $1). I am not sure whether this would
signal negatively or positively in an interview, though.

If the words "shell script" in your question can be understood to mean
"a file containing shell commands that the current shell could source"
(leveraging the debatable ambiguity in formulation), then perhaps
something as simple as this is enough to set your environment variable:

name=foo value=bar; eval "export $name=$value"

Running a new bash instance from the current shell:

bash -c "echo .\$$name.; env | grep \$$name"

confirms the exportation of name=value to the subprocess:

.bar.
foo=bar


On 03/07/18 15:44, Greg Wooledge wrote:
> Before even reading the body, responding only to the subject:
>
>   Use an associative array instead.
>
> On Tue, Jul 03, 2018 at 10:09:24PM +1000, Robert Durkacz wrote:
>> How could I write a shell script that takes two arguments, the first to be
>> interpreted as the name of an environment variable and the second to be the
>> value of that variable? All the script should do is create an environment
>> variable with that value.
> A script CAN'T set an environment variable.  Once the script exits, that
> variable will be gone.
>
> A script is a separate child process with its own copy of the environment,
> and any changes it makes to its environment will not be visible to its
> caller.



reply via email to

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