"env" bash中"echo"的奇怪行为 [英] strange behavior of 'echo' in 'env' bash
问题描述
当我在'env'命令中尝试echo变量时,我什么都没得到,但是我可以使用'printenv'命令看到它:
When I am trying echo variable inside 'env' command I got nothing, but I can see it using 'printenv' command:
root@devel:~# env xxx=23 echo $xxx
root@devel:~# env xxx=23 printenv | grep xxx
xxx=23
这是怎么了?
推荐答案
env xxx=23 echo $xxx
在上面,shell在执行env
之前先评估$xxx
.因此,没有任何回声.
In the above, the shell evaluates $xxx
before env
is executed. Thus, nothing is echoed.
更详细地,外壳程序看到四个词env
,xxx=23
,echo
和$xxx
.它将env
解释为命令名称,并将xxx=23
,echo
和$xxx
解释为将传递给命令env
的三个参数.在将$xxx
传递给命令env
之前,它会进行评估.
In more detail, the shell sees the four words env
, xxx=23
, echo
and $xxx
. It interprets env
as a command name and xxx=23
, echo
, and $xxx
as three arguments which will be passed to the command env
. It evaluates $xxx
before passing it to the command env
.
相比之下,在下文中,没有要评估的Shell变量.而是使用两个自变量xxx=23
和printenv
执行env
. env
设置环境变量xxx
,然后执行printenv
:
By contrast, in the following, there are no shell variables for the shell to evaluate. Instead env
is executed with two arguments, xxx=23
and printenv
. env
sets the environment variable xxx
and then executes printenv
:
$ env xxx=23 printenv | grep xxx
xxx=23
类似地,观察:
$ env xxx=23 sh -c 'echo $xxx'
23
由于$xxx
在单引号内,因此外壳程序不对其进行求值.而是运行带有四个参数的env
:xxx=23
,sh
,-c
和echo $xxx
. env
设置环境变量xxx
后,它将使用参数-c
和echo $xxx
执行sh
.在执行sh
时对$xxx
进行求值,因此它会看到变量xxx
.
Since $xxx
is inside single-quotes, the shell does not evaluate it. Instead is runs env
with four arguments: xxx=23
, sh
, -c
, and echo $xxx
. After env
sets environment variable xxx
, it executes sh
with arguments -c
and echo $xxx
. The $xxx
is evaluated when sh
is executed and hence it sees the variable xxx
.
这篇关于"env" bash中"echo"的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!