简体   繁体   English

使用env和在命令前加上变量分配有什么区别?

[英]What's the difference between using env and preceding a command with variable assignments?

When I want to change the environment of a command I execute in bash, I can just precede it with a variable assignment. 当我想更改在bash中执行的命令的环境时,可以在其前面加上变量赋值。 So for example, if I temporarily want to set the CLICOLOR variable I can do this: 因此,例如,如果我临时要设置CLICOLOR变量,则可以执行以下操作:

CLICOLOR=1 ls

But I could also do this 但我也可以这样做

env CLICOLOR=1 ls

Both result in the same result, so I wonder if there is any difference? 两者都得出相同的结果,所以我想知道是否存在差异? Why do people use one over the other? 人们为什么要一个使用另一个? Is it because of portability, or are there any differences when using output redirection or piping, etc? 是因为可移植性,还是使用输出重定向或管道传输等时有任何区别?

This is mainly so that you don't have to run the shell just to set a variable. 这主要是因为您不必为了设置变量而运行Shell。 Many tools allow you to run a single command to perform a specific task (cron job, build system, internal scripting or macro languages for various tools) and you want to minimize the performance impact and security surface for such scenarios. 许多工具允许您运行单个命令来执行特定任务(各种工具的cron作业,构建系统,内部脚本或宏语言),并且您希望最大程度地降低此类情况对性能的影响和安全性。

Both result in the same result, .. 两者都导致相同的结果,..

No ! 不行

.. , so I wonder if there is any difference? ..,所以我想知道是否有区别?

Yes ! 是的!

Just some trial and error gave some interesting results. 只是一些反复试验就得出了一些有趣的结果。 I think this would supplement @tripleee's answer 我认为这将补充@tripleee的答案

# Where it differs
# PATH=bingo echo "$PATH"
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
# Here the variable expansion happened before setting the PATH
# env PATH=bingo echo $PATH
env: ‘echo’: No such file or directory
# When an `env` is appended in the beginning, the PATH has changed (even)
# before the the full path of echo is resolved, hence the error

Read below points inline with [ this ] answer. 请阅读以下与[this]答案一致的要点。

  • PATH=bingo echo $PATH starts with PATH=bingo which is an assignment . PATH=bingo echo $PATHPATH=bingo开头,这是一个赋值
  • env PATH=bingo echo $PATH starts with env which is not an assignment . env PATH=bingo echo $PATHenv开头,而不是 赋值

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM