问题描述
考虑这个片段:
$ 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.
您的直接选择包括:
SOMEVAR=BBB eval echo zzz '$SOMEVAR' zzz
.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
这篇关于为什么我不能指定环境变量并在同一命令行中回显它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!