How to get the current branch name in Git?

后端 未结 30 2745
清酒与你
清酒与你 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
    0 讨论(0)
  • 2020-11-22 08:10
    git status 
    

    will also give the branch name along with changes.

    e.g.

    >git status
    On branch master // <-- branch name here
    .....
    
    0 讨论(0)
  • 2020-11-22 08:11
    #!/bin/bash
    function git.branch {
      br=`git branch | grep "*"`
      echo ${br/* /}
    }
    git.branch
    
    0 讨论(0)
  • 2020-11-22 08:12

    Over time, we might have a really long list of branches.

    While some of the other solutions are great, Here is what I do (simplified from Jacob's answer):

    git branch | grep \*
    

    Now,

    git status
    

    works, but only If there are any local changes

    0 讨论(0)
  • 2020-11-22 08:12

    I know this is late but on a linux/mac ,from the terminal you can use the following.

    git status | sed -n 1p
    

    Explanation:

    git status -> gets the working tree status
    sed -n 1p -> gets the first line from the status body

    Response to the above command will look as follows:

    "On branch your_branch_name"
    
    0 讨论(0)
  • 2020-11-22 08:13

    Well simple enough, I got it in a one liner (bash)

    git branch | sed -n '/\* /s///p'
    

    (credit: Limited Atonement)

    And while I am there, the one liner to get the remote tracking branch (if any)

    git rev-parse --symbolic-full-name --abbrev-ref @{u}
    
    0 讨论(0)
提交回复
热议问题