bash 将 git 的分支名称附加到命令提示符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/816790/
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
Append git's branch name to command prompt
提问by Piotr Byzia
I wanted to use one of the Git-completion.bash features but I can't customize the look I'd like to have. Here is relevant part of my .bash_profile:
我想使用 Git-completion.bash 功能之一,但我无法自定义我想要的外观。这是我的 .bash_profile 的相关部分:
source ~/.git-completion.bash
function prompt
{
local WHITE="\[3[1;37m\]"
local GREEN="\[3[0;32m\]"
local CYAN="\[3[0;36m\]"
local GRAY="\[3[0;37m\]"
local BLUE="\[3[0;34m\]"
export PS1="
${GREEN}\u${CYAN}@${BLUE}\h ${CYAN}\w $(__git_ps1 '(%s)') ${GRAY}
$ "
}
prompt
and it doesn't show the branch name.
它不显示分支名称。
However, if I replace export PS1 above with the one below, it works as expected:
但是,如果我用下面的替换上面的 export PS1,它会按预期工作:
export PS1='\w$(__git_ps1 "(%s)") > '
I guess it's some apostrophe / quotation marks issue.
我想这是一些撇号/引号问题。
How should I correct the 1st version to get it to work?
我应该如何更正第一个版本以使其正常工作?
回答by pts
The trick to get the quoting right is to have eveything double-quoted, except for $(__git_ps1 "(%s)"), which is single-quoted.
获得正确引用的诀窍是将所有内容都用双引号引起来,除了$(__git_ps1 "(%s)")单引号。
source ~/.git-completion.bash
function prompt
{
local WHITE="\[3[1;37m\]"
local GREEN="\[3[0;32m\]"
local CYAN="\[3[0;36m\]"
local GRAY="\[3[0;37m\]"
local BLUE="\[3[0;34m\]"
export PS1="
${GREEN}\u${CYAN}@${BLUE}\h ${CYAN}\w"' $(__git_ps1 "(%s)") '"${GRAY}"
}
prompt
An alternative solution is to replace $(with \$(in the code in the question.
另一种解决方案是在问题的代码中替换$(为\$(。
Background information: Two substitutions take place: first at export PS1="..."time, and later when the prompt is displayed. You want to execute __git_ps1each time the prompt is displayed, so you have to make sure that the first substitution keeps $(...)intact. So you write either '$(...)'or "\$(...)". These are the two basic ideas behind the solutions I've proposed.
背景信息:发生两次替换:第一次是在export PS1="..."时间,然后是在显示提示时。您希望__git_ps1每次显示提示时都执行,因此您必须确保第一次替换保持$(...)完整。所以,你要么写'$(...)'或"\$(...)"。这是我提出的解决方案背后的两个基本思想。

