How to get the current branch name in Git?

后端 未结 30 2690
清酒与你
清酒与你 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:20

    You have also git symbolic-ref HEAD which displays the full refspec.

    To show only the branch name in Git v1.8 and later (thank's to Greg for pointing that out):

    git symbolic-ref --short HEAD
    

    On Git v1.7+ you can also do:

    git rev-parse --abbrev-ref HEAD
    

    Both should give the same branch name if you're on a branch. If you're on a detached head answers differ.

    Note:

    On an earlier client, this seems to work:

    git symbolic-ref HEAD | sed -e "s/^refs\/heads\///"
    

    Darien 26. Mar 2014

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

    I have a simple script called git-cbr (current branch) which prints out the current branch name.

    #!/bin/bash
    
    git branch | grep -e "^*"
    

    I put this script in a custom folder (~/.bin). The folder is in $PATH.

    So now when I'm in a git repo, I just simply type git cbr to print out the current branch name.

    $ git cbr
    * master
    

    This works because the git command takes its first argument and tries to run a script that goes by the name of git-arg1. For instance, git branch tries to run a script called git-branch, etc.

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

    A less noisy version for git status would do the trick

    git status -bsuno
    

    It prints out

    ## branch-name
    
    0 讨论(0)
  • 2020-11-22 08:22

    One more alternative:

    git name-rev --name-only HEAD
    
    0 讨论(0)
  • 2020-11-22 08:23

    In Netbeans, ensure that versioning annotations are enabled (View -> Show Versioning Labels). You can then see the branch name next to project name.

    http://netbeans.org/bugzilla/show_bug.cgi?id=213582

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

    Found a command line solution of the same length as Oliver Refalo's, using good ol' awk:

    git branch | awk '/^\*/{print $2}'
    

    awk reads that as "do the stuff in {} on lines matching the regex". By default it assumes whitespace-delimited fields, so you print the second. If you can assume that only the line with your branch has the *, you can drop the ^. Ah, bash golf!

    0 讨论(0)
提交回复
热议问题