Skip to content

Instantly share code, notes, and snippets.

@nibocn
Created March 16, 2015 04:48
Show Gist options
  • Save nibocn/d31b8f0e37f5a6600e1c to your computer and use it in GitHub Desktop.
Save nibocn/d31b8f0e37f5a6600e1c to your computer and use it in GitHub Desktop.
在 Shell 提示符中显示 Git 分支

在~/.bashrc中添加如下代码:

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\]'

find_git_branch () {
    local dir=. head
    until [ "$dir" -ef / ]; do
        if [ -f "$dir/.git/HEAD" ]; then
            head=$(< "$dir/.git/HEAD")
            if [[ $head = ref:\ refs/heads/* ]]; then
                git_branch=" → ${head#*/*/}"
            elif [[ $head != '' ]]; then
                git_branch=" → (detached)"
            else
                git_branch=" → (unknow)"
            fi
            return
        fi
        dir="../$dir"
    done
    git_branch=''
}

PROMPT_COMMAND="find_git_branch; $PROMPT_COMMAND"
PS1="$white[$magenta\u$white@$green\h$white:$cyan\w$yellow\$git_branch$white]\n$ $normal"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment