Show just the current branch in Git
I tried looking for a special Git command for this, but I couldn't find one. Is there anything shorter or faster than the following?
git branch | awk '/\*/ { print $2; }'
$ git rev-parse --abbrev-ref HEAD
master
This should work with Git 1.6.3 or newer.
In Git 1.8.1 you can use the git symbolic-ref command with the "--short" option:
$ git symbolic-ref HEAD
refs/heads/develop
$ git symbolic-ref --short HEAD
develop
With Git 2.22 (Q2 2019), you will have a simpler approach: git branch --show-current
.
See commit 0ecb1fc (25 Oct 2018) by Daniels Umanovskis (umanovskis
).
(Merged by Junio C Hamano -- gitster
-- in commit 3710f60, 07 Mar 2019)
branch
: introduce--show-current
display option
When called with
--show-current
,git branch
will print the current branch name and terminate.
Only the actual name gets printed, withoutrefs/heads
.
In detached HEAD state, nothing is output.
Intended both for scripting and interactive/informative use.
Unlikegit branch --list
, no filtering is needed to just get the branch name.
See the original discussion on the Git mailing list in Oct. 2018, and the actual patch.
Warning: as mentioned in the comments by Olivier:
This does not work in every situation!
When you are for instance in a submodule, it does not work.
'git symbolic-ref --short HEAD
' always works.
You may be interested in the output of
git symbolic-ref HEAD
In particular, depending on your needs and layout you may wish to do
basename $(git symbolic-ref HEAD)
or
git symbolic-ref HEAD | cut -d/ -f3-
and then again there is the .git/HEAD
file which may also be of interest for you.