Koller
Koller

Reputation: 43

How to apply an environment variable for the whole command

In my Bash terminal, I regularly execute a chain of commands. For example:

cmd1 && cmd2 && cmd3

Now, I want to define an environment variable which is applied to all three commands and which only scoped to those commands. I tried:

MY_VAR=abc cmd1 && cmd2 && cmd3

But it seems that now only cmd1 sees MY_VAR.

Is there a way to apply the environment variable to all three commands? I know I could export in advance, but I prefer to declare the environment variable locally in an ad-hoc fashion, so it will never impact subsequent commands.

It it matters, I am using urxvt as terminal emulator.

Upvotes: 4

Views: 3778

Answers (4)

Zauxst
Zauxst

Reputation: 51

I've created a simple script to echo my variable to try and simulate a command. Also declared 1 "global environment variable" with the export command.

#!/bin/bash
echo $ABC

Input

$ export ABC=globalEnvironmentVariable
$ (ABC=localGroupVariable; ./test.sh && ./test.sh) && ABC=commandVariable ./test.sh && ./test.sh

Output

localGroupVariable
localGroupVariable
commandVariable
globalEnvironmentVariable

Upvotes: 0

Léa Gris
Léa Gris

Reputation: 19615

The way to do it is:

MY_VAR=abc; cmd1 && cmd2 && cmd3

What makes the difference is the colon after the assignment.

Without the colon ;, MY_VAR=abc cmd1 && ... this cause the assignment to be part of the cmd1 element of the conditional expression. Anything at the other side of the logical AND: && can not see the local environment of the other condition elements.

Upvotes: 1

UtLox
UtLox

Reputation: 4164

You can try this:

export MY_VAR="abc"
cmd1 && cmd2 && cmd3
unset MY_VAR          # only nessesary if you want to remove the variable again

Upvotes: 0

user268396
user268396

Reputation: 11996

Repeat it: MY_VAR=abc cmd1 && MY_VAR=abc cmd2 && MY_VAR=abc cmd3

Or use a subshell:

   # wrapper subshell for the commands
   cmds () 
   {
      cmd1 && cmd2 && cmd3
   }

   # invoke it
   MY_VAR=abc cmds

If you need to enter the whole thing in one go, do:

   cmds() { cmd1 && cmd2 && cmd3; }; MY_VAR=abc cmds

Upvotes: 4

Related Questions