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:
Post by Greg Wooledge
Use an associative array instead.
Post by Robert Durkacz
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