在Bash命令提示符上添加git分支

220

我尝试将我当前正在工作的git分支(已检出)添加到bash提示符中,但没有成功...(同时保持显示活动目录/文件的当前路径不变) 我在我的主目录下有一个 .bashrc 文件,但我也看到很多人提到了 .profile 文件。


4
我认为在Unix/Linux交换中询问会更好。 - Cole Busby
我尝试了大约10个不同的教程,其中一些起作用了,但是我得到了git分支并且失去了之前的工作目录/路径。 - George Katsanos
1
Git 1.9.3+ 带来了一种有趣的显示分支的方式:请参见我的回答 - VonC
谢谢VonC!我已经使用这个工具几个月了,非常好用! - George Katsanos
1
@cole busby 显然不是。 - George Katsanos
1
@GeorgeKatsanos 四年的时间确实让我有所领悟 :p - Cole Busby
16个回答

242

git 1.9.3或更高版本:使用__git_ps1

Git提供了一个名为git-prompt.sh的shell脚本,其中包含一个名为__git_ps1的函数,该函数

打印文本以添加到bash PS1提示符中(包括分支名称)

它的最基本用法是:

$ __git_ps1
(master)

它还可以带有可选的格式字符串:
$ __git_ps1 'git:[%s]'
git:[master]

如何获取

首先,将文件复制到某个地方(例如~/.git-prompt.sh)。

选项1:使用现有的文件副本。示例(Mac OS X 10.15):

$ find / -name 'git-prompt.sh' -type f -print -quit 2>/dev/null
/Library/Developer/CommandLineTools/usr/share/git-core/git-prompt.sh

选项2:从GitHub上拉取脚本from GitHub

接下来,在您的.bashrc/.zshrc中添加以下行:

source ~/.git-prompt.sh

最后,将您的PS1更改为调用__git_ps1作为命令替换符:

Bash:

PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

Zsh:

setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '

git < 1.9.3

请注意,只有 git 1.9.3(2014 年 5 月)或更高版本才能安全地显示该分支名称!

请参见 Richard Hansen (richardhansen)提交 8976500

无论是 bash 还是 zsh 都会对 PS1 的值进行参数扩展命令替换和算术扩展。

在运行两个或三个参数模式时,不要将原始的、未转义的分支名称包含在 PS1 中,而是构造 PS1 引用一个保存分支名称的变量。

由于Shell不会递归展开,这避免了通过特殊构造的分支名称进行任意代码执行。
'$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)'.

什么阴险的人会给分支起这样的名字呢?;) (在xkcd中的“旁边的妈妈”)

更多例子

still_dreaming_1评论中报告:

如果你想要一个带有xterm的彩色提示符,这似乎非常有效(在我的.bashrc中):

PS1='\[\e]0;\u@\h: \w\a\]\n${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\03‌​3[01;34m\]\w\[\033[00m\]$(__git_ps1)\$ ' 

每件事物都是不同的颜色,包括这个分支。

在 Linux Mint 17.3 Cinnamon 64 位中:

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\]$(__git_ps1) \$ ' 

正如J'e评论中所指出的

Ubuntu

Modify PS1 assignments in your bashrc with,

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\033[0;32m$(__git_ps1 " (%s)")\033[0m\$ '

# ---AND--- 

PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(__git_ps1 " (%s)")\$ '

6
当您在 Git 存储库中时,如何设置提示符为当前的 Git 分支。因此,如果您在普通目录中,则显示普通提示符。 - Zubair Alam
1
@still_dreaming_1 你可以很容易地升级或编译 git:http://stackoverflow.com/a/24847953/6309 - VonC
3
如果你想在xterm中使用彩色提示符,这个看起来非常好用(在.bashrc中):PS1='\[\e]0;\u@\h: \w\a\]\n${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]$(__git_ps1)\$' 所有的东西都是不同的颜色,包括分支。 - still_dreaming_1
8
我发布的那个PS1在Linux Mint 17.3 Cinnamon 64位系统中已经不能正确显示了,但是这个可以:PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\]$(__git_ps1) \$ ' - still_dreaming_1
3
当前主版本在https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh - 我认为我们应该在答案中提供链接,以防未来发现漏洞?另外:我不得不在我的PS1行中转义$和",但这可能是由于它的复杂性。 - ArchimedesMP
显示剩余10条评论

76

按照以下步骤进行操作:(Linux)

编辑文件~/.bashrc,在末尾输入以下内容(如果是Mac,则文件为~/.bash_profile

# Git branch in prompt.
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

现在,打开一个新的终端窗口,尝试进入任何一个 Git 仓库。当前分支将会显示在提示符中。

4 更多信息 - MAC/Linux


我认为在OSX上,不必更改/.bash_profile而是改/.bashrc。 - bergercookie
2
请参考以下链接:http://apple.stackexchange.com/questions/119711/why-doesnt-mac-os-x-source-bashrc 和 http://apple.stackexchange.com/questions/51036/what-is-the-difference-between-bash-profile-and-bashrc。 - parasrish
3
对于颜色,请考虑在上面的parse_git_branch中将“git branch”更改为“git -c color.ui=always branch”。它具有与git branch用于突出显示当前分支的相同颜色。 - awatts
受到您的启发,但我喜欢我的工作目录是完整路径(\w),并带有蓝色高亮显示。示例:https://gist.github.com/rmharrison/1885ef6bbb0226eb7b42e2135d5eeca2 - rmharrison
对于MAC,我必须在$(parse_git_branch)之前消除转义字符才能使其正常工作,因此:PS1="\u@\h \W\[\033[32m\]$(parse_git_branch)\[\033[00m\] $ "。虽然我也没有在PS1前面使用'export'。 - Chris
显示剩余7条评论

44

1- 如果你没有 bash-completion ... : sudo apt-get install bash-completion

2- 编辑你的 .bashrc 文件并检查(或添加):

if [ -f /etc/bash_completion ]; then
  . /etc/bash_completion
fi

3- 在你的提示符之前添加以下代码:export PS1='$(__git_ps1) \w\$ '
(__git_ps1 将显示你的 Git 分支)

4- 运行命令:source .bashrc

编辑:

进一步阅读:不要重复发明轮子


这似乎是我使用Homestead/Vagrant虚拟机的唯一可行方式。 - Iannazzi
在Ubuntu 16.04中运行正常。 - Frug
“不要重复造轮子”的链接很遗憾已经失效了。 - Taylor R
@TaylorR 我已恢复链接。 - VonC

39

这是我如何配置提示符以显示Git状态:

获取git-prompt脚本:

curl -o ~/.git-prompt.sh https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh

并且可以通过在您的 .bashrc 文件中添加以下代码来自定义提示符:

请注意,根据上下文,此翻译可能需要进行调整。

# Load Git functions
source ~/.git-prompt.sh

# Syntactic sugar for ANSI escape sequences
txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White
bldblk='\e[1;30m' # Black - Bold
bldred='\e[1;31m' # Red
bldgrn='\e[1;32m' # Green
bldylw='\e[1;33m' # Yellow
bldblu='\e[1;34m' # Blue
bldpur='\e[1;35m' # Purple
bldcyn='\e[1;36m' # Cyan
bldwht='\e[1;37m' # White
unkblk='\e[4;30m' # Black - Underline
undred='\e[4;31m' # Red
undgrn='\e[4;32m' # Green
undylw='\e[4;33m' # Yellow
undblu='\e[4;34m' # Blue
undpur='\e[4;35m' # Purple
undcyn='\e[4;36m' # Cyan
undwht='\e[4;37m' # White
bakblk='\e[40m'   # Black - Background
bakred='\e[41m'   # Red
badgrn='\e[42m'   # Green
bakylw='\e[43m'   # Yellow
bakblu='\e[44m'   # Blue
bakpur='\e[45m'   # Purple
bakcyn='\e[46m'   # Cyan
bakwht='\e[47m'   # White
txtrst='\e[0m'    # Text Reset

# Prompt variables
PROMPT_BEFORE="$txtcyn\u@\h $txtwht\w$txtrst"
PROMPT_AFTER="\\n\\\$ "

# Prompt command
PROMPT_COMMAND='__git_ps1 "$PROMPT_BEFORE" "$PROMPT_AFTER"'

# Git prompt features (read ~/.git-prompt.sh for reference)
export GIT_PS1_SHOWDIRTYSTATE="true"
export GIT_PS1_SHOWSTASHSTATE="true"
export GIT_PS1_SHOWUNTRACKEDFILES="true"
export GIT_PS1_SHOWUPSTREAM="auto"
export GIT_PS1_SHOWCOLORHINTS="true"

如果您想了解更多信息,可以在此处获取所有的dotfiles:https://github.com/jamming/dotfiles


1
到目前为止最佳答案。 - Basil Musa
@Hesam 你可以更改 PROMPT_BEFORE 环境变量并删除 $txtwht\w。我不是很确定,但我猜它会起作用。 - jaguililla
1
它在我的Mac上运行,但显示分支名称为(master * $% =) - Ajak6
这些符号表示分支状态,例如:$ 表示有存储的更改,而 = 表示最新提交已推送到远程跟踪分支。 - jaguililla

11

8

首先,在你的主目录下打开你的 Bash 配置文件。使用默认编辑器最简单的方法是打开并编辑你的 bash_profile

例如,我使用以下命令在 VS Code 中打开它: code .bash_profile。

然后,只需将以下代码粘贴到你的 Bash 中即可。

parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

这个函数

parse_git_branch()

将获取分支名称,并通过PS1在您的终端中显示它。

这里,

\u = 用户名

@ = 静态文本

\h = 计算机名称

\w = 当前目录

$ = 静态文本

您可以更改或删除这些变量以进行更多自定义。


如果您在终端中第一次使用Git或立即配置后,有时可能无法看到分支名称。

如果出现此问题,请不用担心。在这种情况下,只需创建一个样本存储库并在进行一些更改后提交它。当执行提交命令后,终端将从那时开始找到git分支。


屏幕截图:Git分支在终端中


7
root:~/project#  -> root:~/project(dev)# 

请将以下代码添加到您的~/.bashrc文件的末尾:
force_color_prompt=yes
color_prompt=yes
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
fi
unset color_prompt force_color_prompt

我喜欢这个答案不会在当前目录不是仓库的一部分时破坏着色,而其他答案则会。 - Ceco

4

我希望得到一个干净的解决方案,它可以在不替换现有提示的情况下追加内容。与其他解决方案一样,在您的 .bashrc 文件的底部添加此代码。

# function
parse_git_branch() {
  if [ -n "$(git rev-parse --git-dir 2> /dev/null)" ]; then
    echo ">> $(git rev-parse --abbrev-ref HEAD) >>"
  fi
}

# environment customization
export PS1="\$(parse_git_branch)\n$PS1"

进行这个设置后,提示符看起来像

>> branchname >>
user@host:~/current/path$

此外,我想在提示中加入一些颜色,以便更好地突出显示,就像这样

export PS1="\e[0;36m\$(parse_git_branch)\e[0m\n$PS1"

这会导致分支名称以青色(CYAN)显示。


2
vim ~/.bash

parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $"

要反映最新的更改,请运行以下命令

source ~/.bashrc

输出:

chandrakant@NDL41104 ~/Chandrakant/CodeBase/LaravelApp (development) $

1

如果你使用 fish shell,那就非常简单明了。 Fish 是一款交互式的 Shell,自带很多好处。你可以使用apt-get命令来安装。

sudo apt-get install fish

然后,您可以使用以下命令更改提示设置

> fish_config 
Web config started at 'http://localhost:8001/'. Hit enter to stop.
Created new window in existing browser session.

现在前往 http://localhost:8001/ 打开命令提示符选项卡并选择经典+git选项

enter image description here

现在点击使用提示按钮,你就可以开始了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接