在我的 Bash 终端中,我会定期执行一系列命令。例如:
cmd1 && cmd2 && cmd3
现在,我想定义一个适用于所有三个命令且仅适用于这些命令的环境变量。我试过:
MY_VAR=abc cmd1 && cmd2 && cmd3
但现在似乎只cmd1
看到了MY_VAR
。
有没有办法将环境变量应用于所有三个命令?我知道我可以export
提前,但我更喜欢以临时方式在本地声明环境变量,因此它永远不会影响后续命令。
重要的是,我urxvt
用作终端仿真器。
在我的 Bash 终端中,我会定期执行一系列命令。例如:
cmd1 && cmd2 && cmd3
现在,我想定义一个适用于所有三个命令且仅适用于这些命令的环境变量。我试过:
MY_VAR=abc cmd1 && cmd2 && cmd3
但现在似乎只cmd1
看到了MY_VAR
。
有没有办法将环境变量应用于所有三个命令?我知道我可以export
提前,但我更喜欢以临时方式在本地声明环境变量,因此它永远不会影响后续命令。
重要的是,我urxvt
用作终端仿真器。
重复: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
你可以试试这个:
export MY_VAR="abc"
cmd1 && cmd2 && cmd3
unset MY_VAR # only nessesary if you want to remove the variable again
这样做的方法是:
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.
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
$ export ABC=globalEnvironmentVariable
$ (ABC=localGroupVariable; ./test.sh && ./test.sh) && ABC=commandVariable ./test.sh && ./test.sh
localGroupVariable
localGroupVariable
commandVariable
globalEnvironmentVariable