How to insert an environment variable inside the bash prompt

橙三吉。 提交于 2019-11-30 21:35:19

问题


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

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

The prompt does not change when I change the environment variable: $FOO because the $FOO variable is not interpreted.

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:

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

Can this be done in one line?


回答1:


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

export PS1="[\$FOO]$ "

instead of:

export PS1="[$FOO]$ "

Note the \ before the $FOO.




回答2:


Try setting the PROMPT_COMMAND variable:

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.



来源:https://stackoverflow.com/questions/7359652/how-to-insert-an-environment-variable-inside-the-bash-prompt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!