bash 在bash one-liner中为多个命令设置环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14024798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:04:58  来源:igfitidea点击:

Setting environment variables for multiple commands in bash one-liner

linuxbashcommand-line

提问by Pavel K.

Let's say I have following command

假设我有以下命令

$> MYENVVAR=myfolder echo $MYENVVAR && MYENVVAR=myfolder ls $MYENVVAR

$> MYENVVAR=myfolder echo $MYENVVAR && MYENVVAR=myfolder ls $MYENVVAR

I mean that MYENVVAR=myfolder repeats

我的意思是 MYENVVAR=myfolder 重复

Is it possible to set it once for both "&&" separated commands while keeping the command on one line?

是否可以在将命令保留在一行的同时为两个“&&”分隔的命令设置一次?

回答by Jonathan Leffler

Assuming you actually need it as an environment variable (even though the example code does not really need an environment variable; some shell variables are not environment variables):

假设您实际上需要它作为环境变量(即使示例代码并不真正需要环境变量;一些 shell 变量不是环境变量):

(export MYENVVAR=myfolder; echo $MYENVVAR && ls $MYENVVAR)

If you don't need it as an environment variable, then:

如果您不需要它作为环境变量,则:

(MYENVVAR=myfolder; echo $MYENVVAR && ls $MYENVVAR)

The parentheses create a sub-shell; environment variables (and plain variables) set in the sub-shell do not affect the parent shell. In both commands shown, the variable is set once and then used twice, once by each of the two commands.

括号创建一个子壳;在子 shell 中设置的环境变量(和普通变量)不会影响父 shell。在显示的两个命令中,变量设置一次,然后使用两次,两个命令中的每一个都使用一次。

回答by Leonid Volnitsky

Parentheses spawn new proces, where you can set its own variables:

括号产生新的过程,您可以在其中设置自己的变量:

( MYENVVAR=myfolder; echo  1: $MYENVVAR; ); echo  2: $MYENVVAR;
1: myfolder
2:

回答by Basile Starynkevitch

Did you consider using exportlike

您是否考虑过使用export 之类的

export MYENVVAR=myfolder

then type your commands like echo $MYENVVAR(that would work even in sub-shells) etc

然后输入您的命令echo $MYENVVAR(即使在子外壳中也可以使用)等