Bash:在命令行上指定echo的环境变量? [英] Bash: specifying environment variables for echo on command line?

查看:398
本文介绍了Bash:在命令行上指定echo的环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个片段:

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

这里我设置了 $ SOMEVAR AAA 在第一行 - 当我回应它在第二行,我得到 AAA 内容为预期。



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

  $ SOMEVAR = BBB echo zzz $ SOMEVAR zzz 
zzz AAA zzz
pre>

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



这是怎么回事?如果是这样,那么你可以指定诸如 LD_PRELOAD = / ...程序args ... 等变量的变量我缺少什么?

解决方案

你看到的是预期的行为。麻烦的是,在调用具有修改的环境的命令之前,父shell在命令行上评估 $ SOMEVAR 。您需要获得 $ SOMEVAR 的评估,直到环境设置为止。



您的即时选项包括:


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

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



另一个选项是使用子shell符号(as也由 Marcus Kuhn 在他的 answer ):

 (SOMEVAR = BBB; echo zzz $ SOMEVAR zzz)

变量仅在子shell中设置


Consider this snippet:

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

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.

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

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

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?

解决方案

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.

Your immediate options include:

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

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).

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

(SOMEVAR=BBB; echo zzz $SOMEVAR zzz)

The variable is set only in the sub-shell

这篇关于Bash:在命令行上指定echo的环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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