"env" bash中"echo"的奇怪行为 [英] strange behavior of 'echo' in 'env' bash

查看:115
本文介绍了"env" bash中"echo"的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在'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.

更详细地,外壳程序看到四个词envxxx=23echo$xxx.它将env解释为命令名称,并将xxx=23echo$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=23printenv执行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=23sh-cecho $xxx. env设置环境变量xxx后,它将使用参数-cecho $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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆