Why can't I specify an environment variable and echo it in the same command line?

sdaau picture sdaau · Jun 7, 2012 · Viewed 36.6k times · Source

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?

Answer

Jonathan Leffler picture Jonathan Leffler · Jun 7, 2012

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:

  1. SOMEVAR=BBB eval echo zzz '$SOMEVAR' zzz.
  2. 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