Fel*_*sén 6 bash prompt git bashrc
在我的 16.04 安装中,我把它放在我的~/.bashrc
文件中:
#Show git branch in commandline
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u:\[\033[01;34m\]\w\[\033[00m\]\$(parse_git_branch)\[\033[00m\] $ "
Run Code Online (Sandbox Code Playgroud)
它显示了这样的提示:
user:~/myrepo (master) $
Run Code Online (Sandbox Code Playgroud)
但是当我在 18.04 上做同样的事情时,提示看起来像这样:
user:~/myrepo $
Run Code Online (Sandbox Code Playgroud)
我如何让它在 18.04 中工作?
$ printf "%q\n" "$PS1" "$PROMPT_COMMAND" "$0" "$SHELL"
\\\[\\033\[01\;32m\\\]\\u:\\\[\\033\[01\;34m\\\]\\w\\\[\\033\[00m\\\]\$\(parse_git_branch\)\\\[\\033\[00m\\\]\ \$\
''
bash
/bin/bash
Run Code Online (Sandbox Code Playgroud)
我正在使用sed (GNU sed) 4.4
和GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
。这是一个“全新”安装,因此.bashrc
.
Per*_*uck 13
虽然你已经解决了这个问题,但我想介绍一下 git 已经附带的解决方案:
与 git 一起/usr/lib/git-core/git-sh-prompt
安装文件。几年前它在contrib目录中,但同时它进入了官方路径。该文件并不意味着要执行的(事实上,它没有x
标志),而是将采购从.bashrc
。它定义了一些函数来处理漂亮的提示,最突出的是__git_ps1
.
您可以将以下行添加到您的.bashrc
:
source /usr/lib/git-core/git-sh-prompt
export PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u:\[\033[01;34m\]\w\[\033[00m\]\$(__git_ps1)\[\033[00m\] $ "
Run Code Online (Sandbox Code Playgroud)
文件的顶部/usr/lib/git-core/git-sh-prompt
给出了一些其他可以做的描述。我的版本说1) Copy this file to somewhere (e.g. ~/.git-prompt.sh).
但这不是必需的(说明已过时)。
您还可以设置一些环境变量来改变函数的行为。例如,我使用
export GIT_PS1_SHOWDIRTYSTATE=yes
Run Code Online (Sandbox Code Playgroud)
结果如下:
# clean
pduck:~/oss/rsyslog (master) $
Run Code Online (Sandbox Code Playgroud)
或者
# dirty
pduck:~/oss/rsyslog (master *) $
Run Code Online (Sandbox Code Playgroud)
或者
# something added to index
pduck:~/oss/rsyslog (master +) $
Run Code Online (Sandbox Code Playgroud)
或者
# in a completely fresh repo
pduck:~/oss/xxx (master #) $
Run Code Online (Sandbox Code Playgroud)
顺便说一句:获取当前分支的“正确”方法不是解析git branch
的输出,因为这可能会随着新的 git 版本而改变。
git branch
是一个所谓的瓷器命令,这意味着它的输出很好很漂亮,但不能保证在不同版本中保持相同。因此,git 人员推荐用于脚本编写的管道工具。通过管道可以确定当前分支
if [ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" = "true" ]; then
current_branch=$(git symbolic-ref --quiet --short HEAD || git rev-parse --short HEAD)
else
current_branch=""
fi
Run Code Online (Sandbox Code Playgroud)
如果 HEAD 是符号引用(即:签出分支或标记),则第一个赋值有效。如果您检出没有标签的内容(例如git checkout HEAD^^
),则它会失败,而我们会使用它git rev-parse --short HEAD
来显示 SHA1。在if
检查我们是否在所有的(因为别的命令不作任何意义上的)一个Git工作目录。