Let's say I have following command
假设我有如下命令
$> MYENVVAR=myfolder echo $MYENVVAR && MYENVVAR=myfolder ls $MYENVVAR
$> MYENVVAR= MYENVVAR=myfolder echo $MYENVVAR && MYENVVAR=myfolder ls $MYENVVAR
I mean that MYENVVAR=myfolder repeats
MYENVVAR=重复文件夹
Is it possible to set it once for both "&&" separated commands while keeping the command on one line?
是否可以对“&&”两个分开的命令设置一次,同时将命令保持在一行?
3 个解决方案
#1
21
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):
假设您实际上需要它作为环境变量(即使示例代码实际上并不需要环境变量;有些壳变量不是环境变量):
(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中设置的环境变量(和普通变量)不会影响父shell。在显示的两个命令中,变量被设置一次,然后被两个命令分别使用两次。
#2
2
Parentheses spawn new proces, where you can set its own variables:
圆括号产生了新的过程,在这里你可以设置自己的变量:
( MYENVVAR=myfolder; echo 1: $MYENVVAR; ); echo 2: $MYENVVAR;
1: myfolder
2:
#3
0
Did you consider using export like
你考虑过使用export like吗
export MYENVVAR=myfolder
then type your commands like echo $MYENVVAR
(that would work even in sub-shells) etc
然后输入您的命令,如echo $MYENVVAR(即使在子shell中也可以)等
#1
21
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):
假设您实际上需要它作为环境变量(即使示例代码实际上并不需要环境变量;有些壳变量不是环境变量):
(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中设置的环境变量(和普通变量)不会影响父shell。在显示的两个命令中,变量被设置一次,然后被两个命令分别使用两次。
#2
2
Parentheses spawn new proces, where you can set its own variables:
圆括号产生了新的过程,在这里你可以设置自己的变量:
( MYENVVAR=myfolder; echo 1: $MYENVVAR; ); echo 2: $MYENVVAR;
1: myfolder
2:
#3
0
Did you consider using export like
你考虑过使用export like吗
export MYENVVAR=myfolder
then type your commands like echo $MYENVVAR
(that would work even in sub-shells) etc
然后输入您的命令,如echo $MYENVVAR(即使在子shell中也可以)等