我可以在 Zsh 中为子 shell 或复合命令设置环境变量吗?
Can I set in Zsh an environment variable just for a subshell or a compound command?
我想 运行 两个命令 x 和 y,并为它们定义一个环境变量 V。在 zsh 中有简单的方法吗? "bash-like" 解决方案,即
(export V=myvalue; x; y)
很麻烦,只能使用子外壳,而不是复合。但是,以下两个版本在语法上是无效的:
V=myvalue ( x ; y ) # No!
V=myvalue { x ; y } # No!No!No!
没有至少一些额外的代码是不可能的。
通过预先分配变量来修改环境仅适用于 Simple Commands. Meaning that the first word after the variable assignments needs to be the name of a simple (as in "not complex") command. Complex commands include { list }
and ( list )
contstructs. (See the documentation on Complex Commands 的完整列表)
如果你想修改特定命令列表的环境而不改变你当前的环境shell,我可以想到两种方法来实现
如问题中所述,通过运行 subshell 并显式导出变量,有一个相当直接的解决方案:
(export V=myvalue; x; y)
您可以使用 eval
来避免创建子shell:
V=myvalue eval "x; y"
V=myvalue eval x\; y
与第一个解决方案相比,这也节省了三到四个字符。主要缺点似乎是 eval
.
的参数列表中的补全效果不是很好
有点长,但不长。您可以定义一个函数,然后立即将其作为简单命令调用。
f () { x; y; }; V=foo f
或者,您可以使用匿名函数进行本地导出:
() { local -x V=myvalue; x; y }
我想 运行 两个命令 x 和 y,并为它们定义一个环境变量 V。在 zsh 中有简单的方法吗? "bash-like" 解决方案,即
(export V=myvalue; x; y)
很麻烦,只能使用子外壳,而不是复合。但是,以下两个版本在语法上是无效的:
V=myvalue ( x ; y ) # No!
V=myvalue { x ; y } # No!No!No!
没有至少一些额外的代码是不可能的。
通过预先分配变量来修改环境仅适用于 Simple Commands. Meaning that the first word after the variable assignments needs to be the name of a simple (as in "not complex") command. Complex commands include { list }
and ( list )
contstructs. (See the documentation on Complex Commands 的完整列表)
如果你想修改特定命令列表的环境而不改变你当前的环境shell,我可以想到两种方法来实现
如问题中所述,通过运行 subshell 并显式导出变量,有一个相当直接的解决方案:
(export V=myvalue; x; y)
您可以使用
eval
来避免创建子shell:V=myvalue eval "x; y" V=myvalue eval x\; y
与第一个解决方案相比,这也节省了三到四个字符。主要缺点似乎是
eval
. 的参数列表中的补全效果不是很好
有点长,但不长。您可以定义一个函数,然后立即将其作为简单命令调用。
f () { x; y; }; V=foo f
或者,您可以使用匿名函数进行本地导出:
() { local -x V=myvalue; x; y }