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

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

问题描述

请考虑以下代码段:

$ 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?

推荐答案

您看到的是预期的行为.问题在于父外壳程序在使用修改后的环境调用命令之前会在命令行上评估$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'.
  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).

另一种选择是使用子外壳符号(也由 Marcus Kuhn 在其 answer ):

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

(SOMEVAR=BBB; echo zzz $SOMEVAR zzz)

仅在子外壳中设置变量

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

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