简体   繁体   中英

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. So for example, if I temporarily want to set the CLICOLOR variable I can do this:

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. 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.

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

# 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.

  • PATH=bingo echo $PATH starts with PATH=bingo which is an assignment .
  • env PATH=bingo echo $PATH starts with env which is not an assignment .

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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