在终端进行 git 操作的时候,难免会进行分支的切换。切来切去的就会忘记当前所在的分支了。下面我们就在终端中加入 git 的分支信息。

Mac OS

~/.bash_profile 文件中添加以下代码:

  1. # Show current git branch name
  2. parse_git_branch() {
  3. git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
  4. }
  5. export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $ "

Ubuntu

~/.bashrc 文件中添加以下代码:

  1. # Show git branch name
  2. force_color_prompt=yes
  3. color_prompt=yes
  4. parse_git_branch() {
  5. git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
  6. }
  7. if [ "$color_prompt" = yes ]; then
  8. PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ '
  9. else
  10. PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
  11. fi
  12. unset color_prompt force_color_prompt

reference

Git branch name in Linux/Mac Terminal