击:指定为回显命令行环境变量? [英] Bash: specifying environment variables for echo on command line?

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

问题描述

考虑这个片断:

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

不过,如果我尝试指定相同的命令行上的变量回声

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 = / ...变量程序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?

提前任何答复,非常感谢结果
干杯!

Many thanks in advance for any answers,
Cheers!

推荐答案

您看到的是预期的行为。麻烦的是,父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回声ZZZ'$ SOMEVARZZZ

  2. SOMEVAR = BBB SH -c'回声ZZZ $ SOMEVAR ZZZ

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

这两个用单引号prevent从评估母贝 $ 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).

另一种选择是使用子壳符号(如也由马库斯库恩在他<建议HREF =htt​​p://stackoverflow.com/a/14400951/15168>回答):

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

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

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