1

在我的 Bash 终端中,我会定期执行一系列命令。例如:

cmd1 && cmd2 && cmd3

现在,我想定义一个适用于所有三个命令且仅适用于这些命令的环境变量。我试过:

MY_VAR=abc cmd1 && cmd2 && cmd3

但现在似乎只cmd1看到了MY_VAR

有没有办法将环境变量应用于所有三个命令?我知道我可以export提前,但我更喜欢以临时方式在本地声明环境变量,因此它永远不会影响后续命令。

重要的是,我urxvt用作终端仿真器。

4

4 回答 4

4

重复:MY_VAR=abc cmd1 && MY_VAR=abc cmd2 && MY_VAR=abc cmd3

或者使用子shell:

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

   # invoke it
   MY_VAR=abc cmds

如果您需要一次性输入整个内容,请执行以下操作:

   cmds() { cmd1 && cmd2 && cmd3; }; MY_VAR=abc cmds
于 2019-07-27T09:06:59.180 回答
0

你可以试试这个:

export MY_VAR="abc"
cmd1 && cmd2 && cmd3
unset MY_VAR          # only nessesary if you want to remove the variable again
于 2019-07-27T09:23:58.703 回答
0

这样做的方法是:

MY_VAR=abc; cmd1 && cmd2 && cmd3

不同之处在于赋值后的冒号。

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.

于 2019-07-27T11:20:42.340 回答
0

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
于 2019-07-28T01:02:36.360 回答