配置Mac/Linux命令行中的Git显示当前Branch名称

目录

问题

用过git for windows的都知道它可以在git repo目录下自动显示当前的branch名称,而且当前目录和命令缓冲区分两行显示:
在Mac中装了git之后默认并不会有以上特性,如何让Mac的Terminal也可以这样显示呢?

方案

要实现这个功能得先弄清楚为什么git for windows会有以上的显示,在dollar符号前面的那一串字符实际上是环境变量PS1的内容,PS1全称Prompt String 1,即提示字符串,一般会配置为显示当前用户名,当前主机名,当前工作目录等信息。

git for windows安装目录的 \GitWP\etc\profile.d目录下有一个叫git-prompt.sh的文件,里面有对PS1变量进行修改的代码,而profile.d这个目录下的脚本是会在启动终端时自动执行的,所以每次打开git-bash都会有以上效果。

只要在Mac上也做类似的设置即可实现相同效果,首先下载git-prompt ,放到home目录下命名为.git-prompt.sh,然后修改你常用的shell对应的profile文件,比如我更想用bash,那么修改~/.bashrc为:

# set for the git prompt
GIT_PS1_SHOWCOLORHINTS="yes"
source ~/.git-prompt.sh

PS1='[\u@\h:\w]$(__git_ps1 " (%s)") \n\$ '

下次启动bash并切换目录到某个git repo下时,就会非常nice地显示当前branch name。

其它参考

PS1常见变量:

  1. \u - User name
  2. \h - Hostname
  3. \w - Current working directory (full path)
  4. \W - Current working directory (basename only)
  5. \n - New line
  6. \t - Current time in 24-hour format (hh:mm:ss)
  7. \s - Shell name (e.g., bash)
  8. ! - Command history number (incrementing index)
  9. $ - Indicates if the user is a regular user ($) or the root user (#`)

shell startup file相关:
Difference Between .bashrc, .bash-profile, and .profile.
Zsh/Bash startup files loading order (.bashrc, .zshrc etc.)