我最近遇到了一些设置环境变量并在同一命令中启动子进程的示例:
$ TEST="test" sh -c 'echo $TEST"
以前,我一直为此使用 env:
$ env TEST="test" sh -c 'echo $TEST"
有人可以指出第一个例子的解释吗? 为此使用 env 有什么好处吗?
最佳答案
使用 env
的理由很少。大多数时候您可以(并且应该)使用更简单的语法:
var=value ... command
这是 Posix 标准,应该可以在任何 Posix 兼容的 shell 中使用(包括 /bin/sh
)。
以下是 env
有用的几种情况:
上述语法在
csh
(或衍生版本)中不起作用,在fish
中也不起作用。因此,在这些非 Posix shell 中,env
是本地环境修改所必需的。env
的-i
参数启动指示的命令,环境仅 包含指定的环境变量。这可用于运行不受信任的命令,而不会通过环境变量泄露信息。 (但要注意:必须设置一些环境变量才能正常运行,从PATH
开始。)env
使用PATH
环境变量将命令名称解析为可执行文件,可能在env
命令行中修改.在不执行路径名解析的上下文中(例如,shebang 行),使用env
(具有正确的完整文件路径)无需知道所有其他可能的可执行文件的精确路径。 (也正是因为这个原因,在shebang线中经常遇到)。env
的参数在调用 env 之前由 shell 展开。因此,还可以计算环境变量的名称,这是使用标准 shell 语法无法实现的:env "$name=$value" command ...
这在从数组(在 bash 中)扩展环境时特别有用:
env -i "${new_env[@]}" command ...
(这里,
new_env
应该是(var1=val1 var2=val2 ...)
)形式的数组
没有命令的 env
将打印出(可能修改过的)环境,每行一个环境变量。我觉得这个功能不是很有用,但它是env
实用程序继续存在的 Posix 基本原理:Some have suggested that env is redundant since the same effect is achieved by:
name=value ... utility [ argument ... ]
The example is equivalent to env when an environment variable is being added to the environment of the command, but not when the environment is being set to the given value. The env utility also writes out the current environment if invoked without arguments. There is sufficient functionality beyond what the example provides to justify inclusion of env.
关于bash - 使用 env 为子 shell 设置变量有优势吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29322463/