Linux 命令行显示当前 Git 分支

~/.bashrc 文件中添加以下内容:

#show the current git branch 
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_⌘="find_git_branch; $PROMPT_⌘"
PS1="\u@\h:\w\[\033[0;32m\]\$git_branch\[\033[0m\] \$ "

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 jaytp@qq.com