Consider this snippet:
$ SOMEVAR=AAA $ echo zzz $SOMEVAR zzz zzz AAA zzz
Here I've set $SOMEVAR
to AAA
on the first line - and when I echo it on the second line, I get the AAA
contents as expected.
But then, if I try to specify the variable on the same command line as the echo
:
$ SOMEVAR=BBB echo zzz $SOMEVAR zzz zzz AAA zzz
... I do not get BBB
as I expected - I get the old value (AAA
).
Is this how things are supposed to be? If so, how come then you can specify variables like LD_PRELOAD=/... program args ...
and have it work? What am I missing?
To print the value of a particular variable, use the command " echo $varname ". To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces.
Select Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter echo %VARIABLE%. Replace VARIABLE with the name of the environment variable.
We can set variables for a single command using this syntax: VAR1=VALUE1 VAR2=VALUE2 ... Command ARG1 ARG2...
What you see is the expected behaviour. The trouble is that the parent shell evaluates $SOMEVAR
on the command line before it invokes the command with the modified environment. You need to get the evaluation of $SOMEVAR
deferred until after the environment is set.
Your immediate options include:
SOMEVAR=BBB eval echo zzz '$SOMEVAR' zzz
.SOMEVAR=BBB sh -c 'echo zzz $SOMEVAR zzz'
.Both these use single quotes to prevent the parent shell from evaluating $SOMEVAR
; it is only evaluated after it is set in the environment (temporarily, for the duration of the single command).
Another option is to use the sub-shell notation (as also suggested by Marcus Kuhn in his answer):
(SOMEVAR=BBB; echo zzz $SOMEVAR zzz)
The variable is set only in the sub-shell
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