注意这种提示现在由
contrib/completion/
原文链接:https://www.f2er.com/bash/392835.htmlgit-prompt.sh
及其__git_ps1_branch_name变量管理。
- Copy this file to somewhere (e.g.
~/.git-prompt.sh
).- Add the following line to your
.bashrc/.zshrc
:
source ~/.git-prompt.sh
- Change your
PS1
to call__git_ps1
as command-substitution:
Bash: PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ ' ZSH: setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '
但请注意,只有git 1.9.3(2014年5月)or later允许您安全地显示该分支名称(!)
见commit 8976500 by Richard Hansen (richardhansen
):
Both bash and zsh subject the value of PS1 to parameter expansion,command substitution,and arithmetic expansion.
Rather than include the raw,unescaped branch name in
PS1
when running in two- or
three-argument mode,constructPS1
to reference a variable that holds the branch name.Because the shells do not recursively expand,this avoids arbitrary code execution by specially-crafted branch names such as
'$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)'.
什么愚蠢的心会命名这样的分支? ;)(Beside a Mom as in xkcd)
still_dreaming_1 reports in the comments:
This seems to work great if you want a color prompt with
xterm
(in my.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)\$ '
Everything is a different color,including the branch.
在Linux Mint 17.3肉桂64位:
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\]$(__git_ps1) \$ '