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:拉取脚本from GitHub。
接下来,将以下行添加到您的.bashrc/.zshrc:
source ~/.git-prompt.sh
最后,将您的PS1 更改为调用__git_ps1 作为命令替代:
重击:
PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
Zsh:
setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '
git
但请注意,只有 git 1.9.3(2014 年 5 月)or later 允许您安全地显示该分支名称(!)
见commit 8976500Richard Hansen (richardhansen):
bash 和 zsh 都对 PS1 的值进行参数扩展、命令替换和算术扩展。
而不是在PS1 中包含原始的未转义分支名称
三参数模式,构造PS1 引用一个保存分支名称的变量。
由于 shell 不会递归扩展,这避免了通过特制分支名称(例如
)执行任意代码
'$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)'.
什么狡猾的头脑会这样命名一个分支? ;) (Beside a Mom as in xkcd)
更多示例
still_dreaming_1 举报in the comments:
如果您想要带有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)\$ '
一切都是不同的颜色,包括树枝。
在 Linux Mint 17.3 Cinnamon 64 位中:
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\]$(__git_ps1) \$ '