在 Shell 提示符中显示 Git 分支名称的方法

2019-09-23 09:27:51于丽

            return
        fi
        dir="../$dir"
    done
    git_branch=''
}

接下来,将这个函数加入到 PROMPT_COMMAND 中,保证 Bash 在创建 prompt 之前调用这个函数取得分支名称:

PROMPT_COMMAND="find_git_branch; $PROMPT_COMMAND"

最后只要重新定义 PS1 变量即可:

# Here is bash color codes you can use
  black=$'[e[1;30m]'
    red=$'[e[1;31m]'
  green=$'[e[1;32m]'
 yellow=$'[e[1;33m]'
   blue=$'[e[1;34m]'
magenta=$'[e[1;35m]'
   cyan=$'[e[1;36m]'
  white=$'[e[1;37m]'
 normal=$'[e[m]'
 
PS1="$white[$magentau$white@$greenh$white:$cyanw$yellow$git_branch$white]$ $normal"

以上的代码你可以放在 ~/.profile 或者 ~/.bash_profile 等文件中即可,我的系统是 Snow Leopard,PS1 定义在 /etc/bashrc 中,所以我直接修改的这个文件。

最终效果如下:

UPDATE – 2010/06/23:

如果你安装了随 Git 附送的 git-completion.sh 子命令自动完成脚本,也可以使用该脚本提供的方法:

export PS1="[u@h W"'$(__git_ps1 " (%s)")'"]$ "

Ubuntu 系统,请参考: /etc/bash_completion.d/git