IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    为 bash 提示符加上 git 状态

    xiezhenye发表于 2017-02-08 09:32:30
    love 0

    在有一次手误合错分支以后,就决定为 bash 提示符加上显示当前分支,以及提交状态,这样就可以更清楚地知道当前在哪个分支,以及是不是 commit 了,是不是 push 了。代码如下:

    function __git_prompt() {
      local s=$(git status -b --porcelain 2>/dev/null)
      if [[ -z "$s" ]]; then
        PS1="\h:\W \u$ "
      else
        local l=$(echo "$s"|wc -l)
        local br=$(echo "$s"|head)
        if [[ "${br%[ahead*}" != "$br" ]]; then
          local np=1
        fi
        br="${br#\#\# }"
        br="${br%...*}"
        if [[ "$l" -gt 1 ]]; then
          local g="(git:\[$(tput setaf 9)\]$br\[$(tput sgr0)\])" # dirty: red
        elif [[ -z "$np" ]]; then
          local g="(git:\[$(tput setaf 10)\]$br\[$(tput sgr0)\])" # clean: green
        else
          local g="(git:\[$(tput setaf 11)\]$br\[$(tput sgr0)\])" # not pushed: yellow
        fi
        PS1="\h:\W \u $g$ "
      fi
    }
    
    
    PROMPT_COMMAND='__git_prompt'
    

    加入到 .bash_profile 即可。这里是按 MacOS 默认的 PS1 基础上改的,实际使用的时候可以根据需要调整。



沪ICP备19023445号-2号
友情链接