为什么我不能指定一个环境变量并在同一个命令行中回显它? [英] Why can't I specify an environment variable and echo it in the same command line?

查看:20
本文介绍了为什么我不能指定一个环境变量并在同一个命令行中回显它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个片段:

$ SOMEVAR=AAA
$ echo zzz $SOMEVAR zzz
zzz AAA zzz

在这里,我在第一行将 $SOMEVAR 设置为 AAA - 当我在第二行回显时,我得到 AAA代码> 内容如预期.

Here I've set $SOMEVAR to AAA on the first line - and when I echo it on the second line, I get the AAA contents as expected.

但是,如果我尝试在与 echo 相同的命令行上指定变量:

But then, if I try to specify the variable on the same command line as the echo:

$ SOMEVAR=BBB echo zzz $SOMEVAR zzz
zzz AAA zzz

...我没有得到我预期的 BBB - 我得到了旧值 (AAA).

... I do not get BBB as I expected - I get the old value (AAA).

事情应该是这样的吗?如果是这样,那么您为什么可以指定像 LD_PRELOAD=/... program args ... 这样的变量并让它工作?我错过了什么?

Is this how things are supposed to be? If so, how come then you can specify variables like LD_PRELOAD=/... program args ... and have it work? What am I missing?

推荐答案

您看到的是预期的行为.问题在于,父shell 在使用修改后的环境调用命令之前,会在命令行上评估$SOMEVAR.您需要将 $SOMEVAR 的评估推迟到环境设置之后.

What you see is the expected behaviour. The trouble is that the parent shell evaluates $SOMEVAR on the command line before it invokes the command with the modified environment. You need to get the evaluation of $SOMEVAR deferred until after the environment is set.

您的直接选择包括:

  1. SOMEVAR=BBB eval echo zzz '$SOMEVAR' zzz.
  2. SOMEVAR=BBB sh -c 'echo zzz $SOMEVAR zzz'.

两者都使用单引号来防止父 shell 评估 $SOMEVAR;它仅在环境中设置后(临时,在单个命令的持续时间内)才被评估.

Both these use single quotes to prevent the parent shell from evaluating $SOMEVAR; it is only evaluated after it is set in the environment (temporarily, for the duration of the single command).

另一种选择是使用 sub-shell 符号(正如 Marcus Kuhn 在他的 答案):

Another option is to use the sub-shell notation (as also suggested by Marcus Kuhn in his answer):

(SOMEVAR=BBB; echo zzz $SOMEVAR zzz)

变量只在子shell中设置

The variable is set only in the sub-shell

这篇关于为什么我不能指定一个环境变量并在同一个命令行中回显它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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