6

With one environment variable it goes like:

bash$> foo=1 echo "$foo"
1

[EDIT: as noted below, even that won't work but worked only because $foo was previously set by some other trial. Should had given "unset foo" between trials.]

But what if one needs to set multiple environment variables in the same command line where the command is started? Like these don't work:

bash$> foo=1 bar=2 echo "$foo $bar"
1

bash$> foo=1 && bar=2 echo "$foo $bar"
1

bash$> (foo=1;foo=2) && echo "$foo $bar"
1 

bash$> (foo=1 && foo=2) && echo "$foo $bar"
1 

Is it possible? (with a script it is obvious)

zimon
  • 171
  • 1
  • 10
  • 1
    Actually, even your first example (`foo=1 echo "$foo"`) doesn't work, you've probably just got `foo` set from a previous run. – IMSoP Nov 01 '16 at 11:19
  • Ah, you are right. I should have used "unset foo" between the trials. – zimon Nov 01 '16 at 12:21

2 Answers2

7

I am assuming that you do not wish these environment variables to be set for the current shell so that subsequent commands cannot be affected by these env vars. What about this:

$ foo=1 bar=2 bash -c 'echo $foo - $bar '
1 - 2

$ echo $foo
<no output>

$ echo $bar
<no output>

Notice that the scope of the environment variables was only limited to bash sub-shell. As shown by the next two commands those env vars did not end up in the current shell.

If you are not concerned about the env vars ending up in the current shell then simply the following would suffice:

$  foo=1; bar=2; echo "$foo $bar"
1 2

$  echo $foo - $bar
1 - 2
Ashutosh Jindal
  • 18,501
  • 4
  • 62
  • 91
  • You don't actually need the `env` here; the key (as pointed out in the question I've proposed as a dupe) is that the `$foo` is in single quotes, and evaluated later by `bash -c`. So `foo=1 bar=2 bash -c 'echo $foo - $bar '` works just fine as well, as would `foo=1 bar=2 some_other_command`. – IMSoP Nov 01 '16 at 11:26
  • @IMSoP, true that. Thanks. Updated answer. – Ashutosh Jindal Nov 01 '16 at 11:28
-1
$ foo=5;bar=6; echo "$foo $bar"
5 6
user3484013
  • 121
  • 1
  • 9
  • 3
    This "permanently" sets `foo` and `bar`, i.e. they will remain 5 and 6 for the rest of the session, and previous values will be lost. This is different from setting them contextually for a particular command. – IMSoP Nov 01 '16 at 11:24