Show just the current branch in Git
Asked Answered
P

13

487

Is there a Git command equivalent to:

git branch | awk '/\*/ { print $2; }'
Patina answered 13/9, 2009 at 15:10 Comment(4)
i think this is the fastes possible way to get current branchFlyer
possible duplicate of How to get current branch name in Git?Eloquent
@Torek - here's another simple task made difficult by Git.Obcordate
The top answer to the link @ChandrayyaGK posted is far slower than this!Afire
E
840
$ git rev-parse --abbrev-ref HEAD
master

This should work with Git 1.6.3 or newer.

Eyestalk answered 13/9, 2009 at 15:39 Comment(9)
Doesn't work for me either, with git-1.6.2.5. git rev-parse --abbrev-ref HEAD => --abbrev-ref 311172491a9a667f9321bdf1c4fe5e22cc6e2c08 (ie rev-parse does not accept --abbrev-ref (not in the man page either))Virgilio
JasonWoof, works for me in 1.6.4.2, need to changelog to see when exactly did it happen ;-)Aspasia
As far as I can tell from the Git logs, this feature was merged in 2009-04-20 and was released with version 1.6.3.Eyestalk
I would really like to understand that, too. How does this actually work? Also, it looks like --abbrev-ref doesn't return anything for any other argument. It can't just possibly have HEAD as an argument.Beaulieu
Note that if you are in a detached symbolic reference (might means that you are in a branch, but checked out previous commit), this command will only return HEAD, not expected masterFenian
doesn't work on a fresh new repo? is there any workaround?Pettway
@wengwengweng I wouldn't expect it to work on a fresh repo. git branch also shows nothing, the message shows 'master' as 'current' but I suspect that is incorrect since there are no commits, and so nothing for there to be a branch for.Minutely
git branch --show-current is the most current way as of Git 2.22?Conventionality
why not symply git branch | grep '\*'Earnest
Q
230

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, without refs/heads.
In detached HEAD state, nothing is output.

Intended both for scripting and interactive/informative use.
Unlike git 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.

Quilmes answered 10/3, 2019 at 14:48 Comment(8)
Finally, what seems like it should have been there from the start, has been added!Visconti
Warning, 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 worksDisunite
@Disunite Good point, merci beaucoup. I have included your comment in the answer for more visibility.Quilmes
@crypdick That is possible, but what is your, err... current git version?Quilmes
@Quilmes good question, but I already hotfixed a solution and spun down the cluster ¯_(ツ)_/¯Revenant
@Disunite It seems to work just fine in submodules for me.Perchance
I put that command into the PS1 environment variable, to show the current branch in the prompt. Though, if I am outside of a Git repository, at any command I get the message fatal: not a git repository (or any of the parent directories): .git. How can I avoid such an annoying message?Ernaernald
@Ernaernald You need to redirect stderr to /dev/null, as done here.Quilmes
W
167

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
Watersick answered 18/9, 2013 at 17:32 Comment(7)
Better than the accepted answer IMO, because it works on repos with no commitsSmog
Getting the error fatal: ref HEAD is not a symbolic ref when running this as a part of a TravisCI buildMortmain
did not seem to work in GIT 1.9.1 ``` git version 1.9.1 fatal: ref HEAD is not a symbolic ref ```Alexei
Works for me: git version 2.16.2.windows.1Akilahakili
For those getting "symbolic ref" error: it's probably because you technically don't have a branch checked out, and are in a 'detached' state: https://mcmap.net/q/11960/-how-do-i-fix-a-git-detached-head . So, if you need the command to exit successfully in detached head state, use the "rev-parse" command in the other answerHeterogamy
This is working for me as of git version 2.10.1.windows.1Superheterodyne
@JeromeDalbert Different, not better. It trades working in one uncommon usecase for working in another even less common usecase: detached head versus no commits. Both have their place.Thrall
A
31

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.

Aspasia answered 13/9, 2009 at 15:22 Comment(6)
You can shorten git rev-parse --symbolic-full-name to git symbolic-ref.Eyestalk
You don't need to use basename or cut; use BR=${BR#refs/heads/} (where BR is name of variable you saved output of git symbolic-ref HEAD).Tessy
Jakub, of course not, provided you have the output in variable.Aspasia
can do git symbolic-ref --short HEAD alsoSoong
This will break if you have slashes in your branch names ("task/foo", "feature/bar"). A bunch of my buildscripts started failing when colleagues decided that slashes were cool...Recalcitrant
@vacri, you mean the one using basename? That's right, probably you need to cut or use Jakub's suggestion if you have it in variable.Aspasia
B
18

From what I can tell, there is no way to natively show just the current branch in Git, so I have been using:

git branch | grep '*'
Bushtit answered 10/4, 2013 at 20:14 Comment(10)
While that works with GNU coreutils, grep '*' is nominally a syntax error. You probably want git branch | sed -n 's/^\* //p' anyway. Or actually, what the OP posted in the first place, which amounts to the same thing.Custommade
@Custommade can you enlighten me about why grep '*' is nominally a syntax error?Ironworks
Just like the plural s in English has no useful meaning on its own, you cannot say "zero or more times" in isolation without something before it. (I thought I remembered that the GNU grep documentation specifically mentions that a lone * at beginning of string is interpreted literally, i.e. as [*] in general regex, but I cannot find this documented now.)Custommade
@JKABC: what @Custommade meant is that '*' is a regular expression and as such it is invalid. You probably want to use '[*]' (that is, character * instead of operator "zero or more times").Kaiserism
@Kaiserism thank you for the clarification, it makes sense to me now. I usually do it by grep '\*'Ironworks
can only cut the branch name with git branch | grep "*" | cut -d' ' -f2Soong
@Bushtit git command works for me. Also, this command works as well git branch | grep ^*Kuehl
for grep lovers :) git branch | grep -oP '(?<=^\* )(.*)$'Conference
@MarinosAn This works only when using git branch --no-column. git branch | grep -oP '(?<=\* )(\S+)' works with and without this option.Leonoreleonsis
git branch --show-current works for me on git version 2.24.3 (Apple Git-128) prints just the full branch name, nothing else.Sixpence
N
7

I guess this should be quick and can be used with a Python API:

git branch --contains HEAD
* master
Naphthalene answered 15/2, 2018 at 15:29 Comment(1)
This does not output the current branch. It outputs the list of branches which happen to point at the commit HEAD points to. And yes, it can overlap, but this could lead to misunderstandings. Create a new branch from where you are and retry your line : two branches. Question asks for "just the current branch".Hellenist
T
3

I'm using

/etc/bash_completion.d/git

It came with Git and provides a prompt with branch name and argument completion.

Tyrelltyrian answered 13/9, 2009 at 15:13 Comment(2)
How can this prompt be activated?Caffeine
In ubuntu, $ source /etc//bash_completion.d/git-prompt File may be named differently on different systems. (Note: source keyword is the same as just . (dot) in bash.)Orlando
S
3

This is not shorter, but it deals with detached branches as well:

git branch | awk -v FS=' ' '/\*/{print $NF}' | sed 's|[()]||g'
Shaky answered 23/5, 2018 at 9:55 Comment(0)
I
2

For those liking aliases: Put the following to your .zshrc so you get easier git command flow:

alias gpsu="git push --set-upstream origin $(git symbolic-ref --short HEAD)"

Integument answered 17/3, 2021 at 14:1 Comment(2)
Exactly what I was looking for. BeautifulCavy
git push -u origin HEAD works; there is no need to specify the branch name exactly and overcomplicate it.Horsehide
C
1

Someone might find this (git show-branch --current) helpful. The current branch is shown with a * mark.

host-78-65-229-191:idp-mobileid user-1$ git show-branch --current
! [CICD-1283-pipeline-in-shared-libraries] feat(CICD-1283): Use latest version of custom release plugin.
 * [master] Merge pull request #12 in CORES/idp-mobileid from feature/fix-schema-name to master
--
+  [CICD-1283-pipeline-in-shared-libraries] feat(CICD-1283): Use latest version of custom release plugin.
+  [CICD-1283-pipeline-in-shared-libraries^] feat(CICD-1283): Used the renamed AWS pipeline.
+  [CICD-1283-pipeline-in-shared-libraries~2] feat(CICD-1283): Point to feature branches of shared libraries.
-- [master] Merge pull request #12 in CORES/idp-mobileid from feature/fix-schema-name to master
Craniometer answered 9/9, 2019 at 8:18 Comment(1)
git branch --show-current works for me on git version 2.24.3 (Apple Git-128)Sixpence
A
1

Since Git v 2.22 you can:

git branch --show-current

Alphabetize answered 28/2 at 8:55 Comment(2)
Yes, I mentioned it five years ago.Quilmes
Ah, didnt catch that. great!Alphabetize
S
0

For completeness, echo $(__git_ps1), on Linux at least, should give you the name of the current branch surrounded by parentheses.

This may be useful is some scenarios as it is not a Git command (while depending on Git), notably for setting up your Bash command prompt to display the current branch.

For example:

/mnt/c/git/ConsoleApp1 (test-branch)> echo $(__git_ps1)
(test-branch)
/mnt/c/git/ConsoleApp1 (test-branch)> git checkout master
Switched to branch 'master'
/mnt/c/git/ConsoleApp1 (master)> echo $(__git_ps1)
(master)
/mnt/c/git/ConsoleApp1 (master)> cd ..
/mnt/c/git> echo $(__git_ps1)

/mnt/c/git>
Secular answered 1/8, 2018 at 2:54 Comment(1)
the item is an alias and should be present for interactive shell scripts. its probably absent for any sort of scripts.Schnorr
L
0

I'm using

git name-rev HEAD

get

HEAD remotes/origin/branch
Lemuelah answered 26/7, 2023 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.