Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 995
sdaau Avatar asked Jun 07 '12 19:06

sdaau


People also ask

Can you set an environment variable and use echo command to print the value?

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.

How do I echo the env variable in CMD?

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.

How do I set an environment variable in one command?

We can set variables for a single command using this syntax: VAR1=VALUE1 VAR2=VALUE2 ... Command ARG1 ARG2...


1 Answers

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

like image 159
Jonathan Leffler Avatar answered Oct 07 '22 20:10

Jonathan Leffler