How to get the current branch name in Git?

git branch

should show all the local branches of your repo. The starred branch is your current branch.


To retrieve only the name of the branch you are on:

git rev-parse --abbrev-ref HEAD

or with Git 2.22 and above:

git branch --show-current

To display only the name of the current branch you're on:

git rev-parse --abbrev-ref HEAD

Reference: Show just the current branch in Git


For my own reference (but it might be useful to others) I made an overview of most (basic command line) techniques mentioned in this thread, each applied to several use cases: HEAD is (pointing at):

  • local branch (master)
  • remote tracking branch, in sync with local branch (origin/master at same commit as master)
  • remote tracking branch, not in sync with a local branch (origin/feature-foo)
  • tag (v1.2.3)
  • submodule (run inside the submodule directory)
  • general detached head (none of the above)

Results:

  • git branch | sed -n '/\* /s///p'
    • local branch: master
    • remote tracking branch (in sync): (detached from origin/master)
    • remote tracking branch (not in sync): (detached from origin/feature-foo)
    • tag: (detached from v1.2.3)
    • submodule: (HEAD detached at 285f294)
    • general detached head: (detached from 285f294)
  • git status | head -1
    • local branch: # On branch master
    • remote tracking branch (in sync): # HEAD detached at origin/master
    • remote tracking branch (not in sync): # HEAD detached at origin/feature-foo
    • tag: # HEAD detached at v1.2.3
    • submodule: # HEAD detached at 285f294
    • general detached head: # HEAD detached at 285f294
  • git describe --all
    • local branch: heads/master
    • remote tracking branch (in sync): heads/master (note: not remotes/origin/master)
    • remote tracking branch (not in sync): remotes/origin/feature-foo
    • tag: v1.2.3
    • submodule: remotes/origin/HEAD
    • general detached head: v1.0.6-5-g2393761
  • cat .git/HEAD:
    • local branch: ref: refs/heads/master
    • submodule: cat: .git/HEAD: Not a directory
    • all other use cases: SHA of the corresponding commit
  • git rev-parse --abbrev-ref HEAD
    • local branch: master
    • all the other use cases: HEAD
  • git symbolic-ref --short HEAD
    • local branch: master
    • all the other use cases: fatal: ref HEAD is not a symbolic ref

(FYI this was done with git version 1.8.3.1)


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