Git 命令行提示符(显示当前分支)

Git 命令行提示符(显示当前分支)

1 原理:利用 __git_ps1 显示分支

Git 官方仓库的 contrib/completion 目录下提供了 git-prompt.sh,其中的 __git_ps1 函数可以在 PS1 中插入当前分支名。使用时将它与 git-completion.bash(提供命令补全)一起 source 进 shell。

__git_ps1 的调用形式为 $(__git_ps1 " (%s)"),%s 会被替换成当前分支名。

1.1 安装脚本(Debian/Ubuntu)

#!/bin/bash wget --no-check-certificate https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh -O ~/.git-prompt.sh wget --no-check-certificate https://raw.githubusercontent.com/git/git/v$(git version | cut -d " " -f 3)/contrib/completion/git-completion.bash -O ~/.git-completion.bash test -x ~/.bashrc || touch ~/.bashrc echo 'source ~/.git-completion.bash' >> ~/.bashrc echo 'source ~/.git-prompt.sh' >> ~/.bashrc echo "PS1='\u@\h:\w\$(__git_ps1 \" (%s)\")\\$\n-> '" >> ~/.bashrc

执行安装脚本并使设置在当前 shell 生效:

bash install.sh source ~/.bashrc

1.2 手动配置

# 1) 下载 git-prompt.sh 到本地(如 ~/.git-prompt.sh) curl -s -o ~/.git-prompt.sh https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh # 2) 添加到 .bashrc/.zshrc source ~/.git-prompt.sh # 3a) 修改 PS1 调用 __git_ps1(Bash) vim ~/.bashrc PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ ' export GIT_PS1_SHOWDIRTYSTATE=1 export GIT_PS1_SHOWCOLORHINTS=1 export GIT_PS1_SHOWUNTRACKEDFILES=1 # Zsh 写法 setopt PROMPT_SUBST; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '

1.3 使用 PROMPT_COMMAND(更快,Bash)

PROMPT_COMMAND='__git_ps1 "\u@\h:\w" "\\\$ "'

zsh 对应使用 precmd 函数:

precmd () { __git_ps1 "%n" ":%~$ " "|%s" }

2 颜色:正确使用变量拼接 PS1

在 PS1 中使用颜色变量时,如果全部用双引号,$(__git_ps1) 会在每次 source 时只求值一次,导致分支无法动态更新。正确做法是:颜色变量用双引号,\u \h \w 等转义符和 $(__git_ps1) 函数用单引号:

# 定义颜色 RED="\[\033[0;31m\]" GREEN="\[\033[0;32m\]" BLUE="\[\033[0;34m\]" LIGHT_GRAY="\[\033[0;37m\]" COLOR_NONE="\[\e[0m\]" # 错误:分支无法动态更新 # PS1="${LIGHT_GRAY}\u@${RED}\h${COLOR_NONE}:${GREEN}\w${BLUE}$(__git_ps1)${COLOR_NONE}\n-> " # 正确 PS1="${LIGHT_GRAY}"'\u@'"${RED}"'\h'"${COLOR_NONE}:${GREEN}"'\w'"${BLUE}"'$(__git_ps1 " (%s)")'"${COLOR_NONE}\n-> "

3 更酷炫的 bash-git-prompt

magicmonty/bash-git-prompt 可以显示当前文件是否更新、分支状态等更多信息:

git clone https://github.com/magicmonty/bash-git-prompt.git ~/.bash-git-prompt --depth=1 echo "source ~/.bash-git-prompt/gitprompt.sh" >> ~/.bashrc echo "GIT_PROMPT_START='\u@\h:\w'" >> ~/.bashrc echo "GIT_PROMPT_END='\n-> '" >> ~/.bashrc echo "GIT_PROMPT_ONLY_IN_REPO=1" >> ~/.bashrc

配置示例:

PS1='\u@\h:\w\n' export LESSCHARSET=utf-8 GIT_PROMPT_START='\u@\h:\w' GIT_PROMPT_END='\n' GIT_PROMPT_ONLY_IN_REPO=1 source ~/.bash-git-prompt/gitprompt.sh

GIT_PROMPT_ONLY_IN_REPO=1 表示只在 Git 仓库目录内启用 git 提示,避免在普通目录里大量 I/O 拖慢提示符。

阅读 — · 全站 —
🎸 我的歌单 0 首