如何在 bash 提示中插入环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7359652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:44:44  来源:igfitidea点击:

How to insert an environment variable inside the bash prompt

bashenvironment-variablesprompt

提问by Bernd

I can set an environment variable inside the bash prompt like this:

我可以在 bash 提示符中设置一个环境变量,如下所示:

export PS1="[\u@\H/$FOO \W]$ "

The prompt does not change when I change the environment variable: $FOObecause the $FOOvariable is not interpreted.

当我改变环境变量时提示没有改变:$FOO因为$FOO变量没有被解释。

I can work around it by doing the following, exporting PS1 again. But I would like to be able to do it on one line:

我可以通过执行以下操作来解决它,再次导出 PS1。但我希望能够在一行上做到这一点:

[user@server ]$ echo $FOO
foo
[user@server ]$ export PS1="[$FOO]$ "
[foo]$ export FOO=bla
[bla]$ 

Can this be done in one line?

这可以在一行中完成吗?

回答by Micha? ?rajer

you need to add backslash to get it evaluated not in the time of FOO assigment but during evaluating the PS1, so do:

您需要添加反斜杠以使其不是在 FOO 分配时而是在评估 PS1 期间对其进行评估,因此请执行以下操作:

export PS1="[$FOO]$ "

instead of:

代替:

export PS1="[$FOO]$ "

Note the \before the $FOO.

请注意\$FOO

回答by Arnaud Le Blanc

Try setting the PROMPT_COMMAND variable:

尝试设置 PROMPT_COMMAND 变量:

prompt() {
    PS1="[$FOO]$ "
}

PROMPT_COMMAND=prompt

From http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x264.html:

Bash provides an environment variable called PROMPT_COMMAND. The contents of this variable are executed as a regular Bash command just before Bash displays a prompt.

来自http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x264.html

Bash 提供了一个名为 PROMPT_COMMAND 的环境变量。在 Bash 显示提示之前,此变量的内容作为常规 Bash 命令执行。