I am trying to invoke a shell command with a modified environment via the command env
.
According to the manual
env HELLO='Hello World' echo $HELLO
should echo Hello World
, but it doesn't. If I do
HELLO='Hello World' bash -c 'echo $HELLO'
it prints Hello World
as expected (thanks to this answer for this info).
What am I missing here?
Cheers, Niklas
The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.
To set (or change) a environment variable, use command " set varname=value ". There shall be no spaces before and after the '=' sign. To unset an environment variable, use " set varname= ", i.e., set it to an empty string.
To set an environment variable everytime, use the export command in the . bashrc file (or the appropriate initialization file for your shell). To set an environment variable from a script, use the export command in the script, and then source the script. If you execute the script it will not work.
It's because in your first case, your current shell expands the $HELLO
variable before running the commands. And there's no HELLO
variable set in your current shell.
env HELLO='Hello World' echo $HELLO
will do this:
$HELLO
'HELLO=Hello World'
, 'echo'
and ''
(an empty string, since there's no HELLO
variable set in the current shell)env
command will run and set the HELLO='Hello World'
in its environmentenv
will run echo
with the argument ''
(an empty string)As you see, the current shell expanded the $HELLO
variable, which isn't set.
HELLO='Hello World' bash -c 'echo $HELLO'
will do this:
HELLO='Hello World
for the following command'-c'
and 'echo $HELLO'
echo $HELLO
$HELLO
in the new bash sub-shell, bash first expands anything it can, $HELLO
in this case, and the parent shell set that to Hello World
for us.echo 'Hello World'
If you tried to do e.g. this:
env HELLO='Hello World' echo '$HELLO'
$HELLO
is enclosed in single quotes'HELLO=Hello World'
, 'echo'
and '$HELLO'
HELLO='Hello World'
in its environment'$HELLO'
In this case, there's no shell that will expand the $HELLO
, so echo
receives the string $HELLO
and prints out that. Variable expansion is done by shells only.
I think what happens is similar to this situation in which I was also puzzled.
In a nutshell, the variable expansion in the first case is done by the current shell which doesn't have $HELLO
in its environment. In the second case, though, single quotes prevent the current shell from doing the variable expansion, so everything works as expected.
Note how changing single quotes to double quotes prevents this command from working the way you want:
HELLO='Hello World' bash -c "echo $HELLO"
Now this will be failing for the same reason as the first command in your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With