让 Shell 命令提示符显示 Git 分支名称

2017-04-30  本文已影响0人  patiencing

缘起

在本地环境( iTerm2 + zsh) 使用终端工具操作 Git 时, 能够显示"当前文件夹名称"以及" Git 分支名称"(如下图).


shell_git_01.jpg

这种设置非常有用, 尤其是需要频繁切换分支时, 能够避免操作错误的分支.
但是使用远程服务器和 Vagrant 虚拟机时没有这个功能.


解决

上网搜索, 在一个博客上找到解决方案.

在 Shell 的配置文件中添加下面代码:

function git-branch-name {
  git symbolic-ref HEAD 2>/dev/null | cut -d"/" -f 3
}
function git-branch-prompt {
  local branch=`git-branch-name`
  if [ $branch ]; then printf " [%s]" $branch; fi
}
PS1="\u@\h \[\033[0;36m\]\W\[\033[0m\]\[\033[0;32m\]\$(git-branch-prompt)\[\033[0m\] \$ "

注意: 上面的 git symbolic-ref HEAD 2>/dev/null | cut -d"/" -f 3 可以改成 git symbolic-ref --short -q HEAD, 更简洁, 而且测试有效. 谢谢风之去向_c305的建议;
为了让大家可以比较前后, 原来的代码就不修改了;

因为远程服务器使用的是 bash, 所以配置文件在 ~/.bashrc, 添加上面的代码之后, 输入 source ~/.bashrc 使配置立即生效.

PS. 可以通过echo $SHELL 命令可以查看系统当前使用的 Shell; 如果使用的是 /bin/zsh,配置文件在 ~/.zshrc, 使用 source ~/.bashrc 来使 zsh 的配置立即生效)

最终的效果是:


shell_git_02.jpg

解读代码

第 1 部分

function git-branch-name {
  git symbolic-ref HEAD 2>/dev/null | cut -d"/" -f 3
}

git symbolic-ref 是 Git 的命令, 表示"符号引用 (symbolic reference), 指向目前所在的分支. 比如命令 git symbolic-ref HEAD 会输出当前的分支, 输出样式像这样: refs/heads/dev

命令执行有两种输出, 一种是正常输出, 一种是错误输出. shell 把正常输出标记为 1, 错误输出标记为 2.
在非 git 工作目录下,‘git symbolic-ref HEAD‘会输出一个错误.

/dev/null 文件在被用作重定向输出时, 表示输出被直接丢弃; 被用作重定向输入时, 表示文件结束.

那么 2>/dev/null 的作用就是:

cut 是 Shell 命令, 表示剪下文本文件的数据; cut -d"/" -f 3 表示分隔符是 /, 以此分隔符来识别分割文本, 取出第 3 段数据;

所以, git symbolic-ref HEAD 识别出的结果是 refs/heads/dev, cut/ 为分隔符分割文本, 分别是 refsheadsdev, 然后取出第 3 段数据, 就是 dev(当前的分支名称)

第 2 部分

function git-branch-prompt {
  local branch=`git-branch-name`
  if [ $branch ]; then printf " [%s]" $branch; fi
}

local 在文档中的解释是:

The local command creates an [incr Tcl] object that is local to the current call frame. When the call frame goes away, the object is auto-matically deleted. This command is useful for creating objects that are local to a procedure.

那么 local 应该是用于声明"局部变量"的. 查阅资料得知, Shell 中函数定义的变量默认是"全局变量", 所以如果要声明"局部变量", 需要用 local 显示声明;

local branch=`git-branch-name`

是指把函数 git-branch-name 获得的值赋给 branch 变量;
注意, 在 Shell 中, 声明变量时不需要加 $, 而且 = 符号两边不能加空格, 在引用变量时, 则需要加上 $, 这就是为什么后面 if [ $branch ]; 需要加 $ 符号的原因.

if [ $branch ]; then printf " [%s]" $branch; fi 表示: 如果存在 $branch 变量, 则将该变量做为字符串打印出来; (PS: shell 的控制结构中, ifelse 判断语句的开头是 if, 结尾是 fi,

第 3 部分

PS1 是 Shell 中的一个特殊变量, 用来表示"提示符", 该变量的可选参数包括:

Shell 输出样式设置:

所以 PS1="\u@\h \[\033[0;36m\]\W\[\033[0m\]\[\033[0;32m\]\$(git-branch-prompt)\[\033[0m\] \$ " 的解读如下:

组成部分是:

颜色设置是:


参考资料


文章历史


如果你觉得我的文章对你有用, 请打个"喜欢", 或者给些改进的建议 _

上一篇 下一篇

猜你喜欢

热点阅读