How to get the current branch name in Git?

后端 未结 30 3145
清酒与你
清酒与你 2020-11-22 07:47

I\'m from a Subversion background and, when I had a branch, I knew what I was working on with \"These working files point to this branch\".

But with Git I\'m not sur

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 08:09

    Sorry this is another command-line answer, but that's what I was looking for when I found this question and many of these answers were helpful. My solution is the following bash shell function:

    get_branch () {
        git rev-parse --abbrev-ref HEAD | grep -v HEAD || \
        git describe --exact-match HEAD 2> /dev/null || \
        git rev-parse HEAD
    }
    

    This should always give me something both human-readable and directly usable as an argument to git checkout.

    • on a local branch: feature/HS-0001
    • on a tagged commit (detached): v3.29.5
    • on a remote branch (detached, not tagged): SHA1
    • on any other detached commit: SHA1

提交回复
热议问题