How do I get the current branch name in Git?
Asked Answered
S

52

4059

How do I get the name of the current branch in Git?

Subnormal answered 5/6, 2011 at 20:13 Comment(11)
Let your IDE display the file .git/HEAD, possibly in a parent directorySanative
stackoverflow.com/questions/1417957/… $ git rev-parse --abbrev-ref HEADCutcherry
possible duplicate of How to programmatically determine the current checked out Git branchAutonomic
With View -> Show versioning Labels enabled in NetBeans, then all you need to do is hover your mouse over the Project (or File, or Favorite) folder to see the current branch.Unesco
Possible duplicate of Show just the current branch in GitExpostulation
git branch --show-current is the wrong solution. I have 2.25.1 and it created a branch in my local repo called --show-current instead of showing the current branchHaynes
@MartijnHiemstra, is it possible you have an alias (either in .gitconfig or .bashrc) set up?Arrears
Hi VonC and @Unesco thank you for your notes - I suggest to use the Answers section to give an answer (not comments). Feel free to delete your comment (and also than feel free to flag my comment as not useful anymore)Syblesybley
Bizar, how much energy for all those clever answers, while the question is so futile, as a simple get status, the most used command, shows the branch you are currently on. Or do you use a smart gui tool that hides git status?Blueprint
git symbolic-ref --short HEAD is the most safe answer. Other answers require caution of exit status and/or printed value with a detached HEAD.Cocci
git rev-parse --abbrev-ref HEADBrute
S
4262
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

Version 2.22 adds the --show-current option to ”print the name of the current branch”. The combination also works for freshly initialized repositories before the first commit:

git branch --show-current
Shonna answered 5/6, 2011 at 20:17 Comment(18)
But that doesnt help me with Notepad++ and Netbeans. Just git bash (and Probobly Vim) and I mentioned that. I'm tring to work with other Ide's and text editors that arent command line.Subnormal
@Subnormal Actually they are helping you except you want something accessible through GUI. Correct?Peafowl
If you're willing to work in Eclipse, there is a program called "eGit" that has a GUI that will tell you the current branch for all repos in it. Otherwise, I don't know.. you would be at the mercy of the creator of whatever plugin you'd want to use that's compatible with your choice of program (if there are any).Shonna
I have done git branch but I see no * on my current branch. Yet if checkout to that branch I will say that I am currently on that branch. What is wrong with my git/terminal?Vanquish
after doing a git checkout --orphan foo then git branch failed to show branch foo. Whereas git symbolic-ref HEAD as suggested another answer worked.Intimacy
I've asked the same type of question here, using a similar approach as possible solution. However, I cannot use the 'grep *' (based on comment by @fboes) in gradle code. Advice anyone?Imbecility
while this answer gives you more detail, it requires a complex script to parse thru. @jistanidiot provided a much more direct, and concise, answerKokand
gitbranch="$( git branch | grep \* )" currentbranch="$([[ "${gitbranch}" == "* (HEAD"* ]] && echo "${gitbranch}" | cut -d ' ' -f5 | cut -d ')' -f1 || echo "${gitbranch}" | cut -d ' ' -f2-)"Caz
downvoted : In my case, I'm using colorized output (I guess this is due to my color.ui=true flag) and when I grep the output, I get special control characters used for colorization. It means that in my case, git checkout $(git branch | grep \* | cut -d ' ' -f2) failsPodium
This is v. slow. The code in the question given here is much faster: stackoverflow.com/questions/1417957/…Margarita
I agree with @boobiq's comment. It can also be done with git branch | grep \* | cut -c3-. This helps with "(no branch)" branch.Ishmaelite
Using porcelain commands in scripts is never the right approach: -1.Neisa
using awk, git branch | awk '{if ($1 == "*") print $2}'Nishanishi
This solution doesn't work after git checkout --orphan branchHemipode
What does git rev-parse --abbrev-ref HEAD do exactly? I was previously using git describe --contains --all HEAD but that breaks sometimes and i'm not quite sure why.Spoliate
I used git rev-parse --abbrev-ref HEAD on script, and it became perfectMousterian
It's worth noting that "git rev-parse --abbrev-ref HEAD" will return something like "heads/master" instead of "master" if for some reason somebody created a tag called master in addition to a branch called master.Wrightson
git branch --show-current works for meTowboat
I
5486

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

Impair answered 27/8, 2012 at 12:33 Comment(26)
Good one, sadly it does not work if you are in a 'detached HEAD' state (it just outputs 'HEAD', which is totally useless).Succinct
I guess by the git internals if you are in a 'detached HEAD' state there is no tracking of the branch it belongs to, because git branch shows * (no branch), which is also useless...Succinct
"git symbolic-ref --short HEAD" also works for this same purposeLazaretto
note: git symbolic-ref --short HEAD doesn't work in pre-1.8 clients. (RHEL6 is currently on v1.7)Cabotage
git rev-parse --abbrev-ref HEAD 2>/dev/null The /dev/null part prevents you from seeing an error if you just created a new repository that has not yet HEAD.Necrosis
This is better than git branch. I don't need to parse the result to get current branch.Grand
All it prints for me is HEAD? I'm on Windows, msysgit.Filia
See stackoverflow.com/questions/18659425/… for getting a tag-name as well.Reportage
Same as @CoDEmanX. This prints HEAD. Using git version 1.8.1.msysgit.1, W7.Transitive
Update: @CoDEmanX I ran git branch and it showed two branches: <no branch> (???) and master. Apparently I was on the former. After switching to master and making sure I was on a branch rather than no branch, this started working. Later update: and now I remember! I was using a detached head :) Hence the no branch :)Transitive
Yet another way, using Unix tools: git branch | grep \* | awk '{print $2}'Intact
git symbolic-ref --short HEAD seems to be more versatile. git rev-parse --abbrev-ref HEAD yields HEAD if the repo is a just-initialized one.Disenthrall
Does not work after a "git checkout -b NAME REF", only shows the sha1. git name-rev HEAD works though.Valentino
Love it! I found the best alias ever for git on os x from this answer. git rev-parse --abbrev-ref HEAD | tr -d '\n' | pbcopyDene
I've found that this works for cloning from SSH but not HTTPS, meaning with HTTPS, I just get HEAD in the console -- v2.9+Camarillo
Can there be no current branch? can this command return empty string ?Salado
@Subnormal please consider accepting this as the solution.Coparcener
@Arioch'The Yes, see all the people complaining that it 'just outputs HEAD'; no it won't return an empty string.Implausible
I thought the current branch and HEAD were one and the same?Cliquish
git branch | grep \* is far more easier to remember than thisEvulsion
@nilesh: that command will include an asterisk. This answer gives the exact branch name (useful for scripting).Leghorn
git branch --contains works for me (but yes, includes the *)Snap
on my machine i get two lines and the second line is filled with -- text. shouldn't the -- be removed from the answer?Breannabreanne
Based on @DylanNicholson's suggestion, I'm using git branch --format='%(refname:short)' --contains | grep -v '^(' but there may still be different branches. Unfortunately, Git does not keep branch information that was present at the time of the commit (before branches diverged). However, if master is present, I assume that this is the correct one, as it exists since the beginning. This solves almost all the practical cases for me.Wingate
Why not just use git branch --show-current though? I'd think almost everybody is using v2.2+ these days...Snap
Love how completely non-intuitive and cryptic this solution is. It works perfectly for me, but is a great illustration of my yearslong frustration with Git and its docs.Kerril
S
4262
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

Version 2.22 adds the --show-current option to ”print the name of the current branch”. The combination also works for freshly initialized repositories before the first commit:

git branch --show-current
Shonna answered 5/6, 2011 at 20:17 Comment(18)
But that doesnt help me with Notepad++ and Netbeans. Just git bash (and Probobly Vim) and I mentioned that. I'm tring to work with other Ide's and text editors that arent command line.Subnormal
@Subnormal Actually they are helping you except you want something accessible through GUI. Correct?Peafowl
If you're willing to work in Eclipse, there is a program called "eGit" that has a GUI that will tell you the current branch for all repos in it. Otherwise, I don't know.. you would be at the mercy of the creator of whatever plugin you'd want to use that's compatible with your choice of program (if there are any).Shonna
I have done git branch but I see no * on my current branch. Yet if checkout to that branch I will say that I am currently on that branch. What is wrong with my git/terminal?Vanquish
after doing a git checkout --orphan foo then git branch failed to show branch foo. Whereas git symbolic-ref HEAD as suggested another answer worked.Intimacy
I've asked the same type of question here, using a similar approach as possible solution. However, I cannot use the 'grep *' (based on comment by @fboes) in gradle code. Advice anyone?Imbecility
while this answer gives you more detail, it requires a complex script to parse thru. @jistanidiot provided a much more direct, and concise, answerKokand
gitbranch="$( git branch | grep \* )" currentbranch="$([[ "${gitbranch}" == "* (HEAD"* ]] && echo "${gitbranch}" | cut -d ' ' -f5 | cut -d ')' -f1 || echo "${gitbranch}" | cut -d ' ' -f2-)"Caz
downvoted : In my case, I'm using colorized output (I guess this is due to my color.ui=true flag) and when I grep the output, I get special control characters used for colorization. It means that in my case, git checkout $(git branch | grep \* | cut -d ' ' -f2) failsPodium
This is v. slow. The code in the question given here is much faster: stackoverflow.com/questions/1417957/…Margarita
I agree with @boobiq's comment. It can also be done with git branch | grep \* | cut -c3-. This helps with "(no branch)" branch.Ishmaelite
Using porcelain commands in scripts is never the right approach: -1.Neisa
using awk, git branch | awk '{if ($1 == "*") print $2}'Nishanishi
This solution doesn't work after git checkout --orphan branchHemipode
What does git rev-parse --abbrev-ref HEAD do exactly? I was previously using git describe --contains --all HEAD but that breaks sometimes and i'm not quite sure why.Spoliate
I used git rev-parse --abbrev-ref HEAD on script, and it became perfectMousterian
It's worth noting that "git rev-parse --abbrev-ref HEAD" will return something like "heads/master" instead of "master" if for some reason somebody created a tag called master in addition to a branch called master.Wrightson
git branch --show-current works for meTowboat
F
593

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

Floodlight answered 8/8, 2012 at 15:55 Comment(8)
As all other answers, this doesn't work when you are in a 'detached HEAD' stateSuccinct
@CarlosCampderrós: if you're in detached HEAD state, there is no such thing as a current branch. After all, the commit that you are in might be reachable by zero, one or more branches.It
this makes problems in empty git repositories when there is no HEADKorns
With git version 2.4.4 git rev-parse --abbrev-ref HEAD shows HEAD when you’re on detached head.Verlie
The best answer is still git symbolic-ref HEAD | sed -e "s/^refs\/heads\///" since it will display a string like HEAD detached at a63917f when in a detached state, unlike the other answers which show either nothing or HEAD. This is important.Jandy
This is also whats used in git-prompt.sh (the branch name that will be displayed in your bash prompt if enabled).Valentino
This works after git checkout --orphan branch unlike the accepted answer.Hemipode
This gives me fatal: ref HEAD is not a symbolic ref. When I cd into the folder, it shows me user@machine:/my/folder ((62d6058...)) >Upwind
C
326

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)

Critique answered 25/10, 2013 at 8:53 Comment(7)
In summary, none seem to do quite what I would by hand.Vermicelli
This was quite helpful for me: git describe --all --exact-match 2>/dev/null | sed 's=.*/==' was the best solution for me (good names for tags and branch heads, no output for random detached heads.Wynd
However, I just discovered that using git describe has a serious failing when there are multiple branches referencing the same commit, e.g. right after git checkout -b foo - it uses one of them arbitrarily (seems like maybe the most recently created one). I will change my strategy to use filtered output from git branch and only use git describe if the result is something about a detached head.Wynd
Actually, I need to use git branch --no-color to make sure that the filename is free of annoying terminal escape codes.Wynd
"current branch" (set by checkout foo) and "current commit" are 2 distinct concepts. symbolic-ref only looks at active branch. describe only looks at a commit, and chooses heuristically from all branches/tags pointing to it (or near it). DWIM commands like branch and status use current branch when defined, but all of them choose heuristically in all "detached HEAD" situations.Wellmannered
Can you add the results of git branch --show-current to this list? The behavior is that when a local branch is checked out, it prints the branch short name (ex: "master"), and otherwise, it prints nothing, returns success.Siderolite
Could you also add git name-rev --name-only HEAD to your list? Another scenario to call out is a newly git init-ed repo.Commutator
A
265

As of version 2.22 of git you could just use:

git branch --show-current

As per man page:

Print the name of the current branch. In detached HEAD state, nothing is printed.

Are answered 7/6, 2019 at 22:9 Comment(10)
Yes, I mentioned that last March in the comments of that page: stackoverflow.com/questions/6245570/…. And in https://mcmap.net/q/12588/-show-just-the-current-branch-in-git.Bystander
At least mention this does not work in detached HEAD state. Just lost hours getting git 2.22 to compile for nothing ...Esoteric
Available since Git version 2.22 : github.com/git/git/blob/master/Documentation/RelNotes/…Sentience
it does not show the branch name. All it is showing is mainDuluth
@KarenGoh It will show main, when you are currently on a branch called main.Are
It doesn't show the branch name. Only when I do git remote -v then it will show the name.Duluth
That is strange. Are you sure that you are running atleast 2.22?Are
but, it doesn't tell you name with this commandDuluth
@DavidDeprost but it is working. When in a detached head state, you aren't on a branch. So showing nothing is a very reasonable response to that. What did you expect to happen?Quadrat
With detached HEAD, the exit code is 0 AND nothing is printed. With symbolic-ref --short HEAD you get a nice fat error message :)Cocci
M
144

One more alternative:

git name-rev --name-only HEAD
Maddi answered 2/11, 2015 at 19:17 Comment(10)
it also can be retrieved with echo ${$(git symbolic-ref --quiet HEAD)#refs/heads/}Transmigrant
It does not work if HEAD is the same for master and feature branch (e.g. during merge). It returns 'master' even if executed on the feature branch.Breakage
git checkout master && git name-rev --name-only HEAD # ac-187 It does not work as expectedMask
I save this into a variable just before merging and also in cases my HEAD might get de-attached if I checkout a particular commit. In these case this works fine.Plymouth
I'm doing this from a Jenkins pipeline. So this appears to be for the time being the best answer for me. Doing git branch --list just says * (HEAD detached at 7127db5). Doing git rev-parse --abbrev-ref HEAD just says HEAD and so on.Chino
And for windows users add | clip to put it on the clipboard.Tripod
I found the version of git makes a difference on this. Mac git version 2.15.2 (Apple Git-101.1) gives only the tag name not the branch: $ /usr/bin/git name-rev --name-only HEAD #=> tags/8.12.0-RC1^0 ; Compare to brew installed git version 2.7.1 correctly gives me my desired branchname.Imponderabilia
I am on Git 2.18.0.windows.1 and for my purpose this seems to be the only answer that does what I need. If my branch is named develop and I happen to be not on the head for some reason (for instance because someone else pushed something) I get "develop~2" or something similar with more intricate code behind the ~. Either way, all I have to do is look for the first ~ and take anything before that. That will always give me the branch name. It is a hack, I would rather have Git tell me the base branch name directly, but while this is not an option I am happy with this solution.Buber
@AlexanderAbashkin It's working for in git version 2.17.1 of this command git checkout master && git name-rev --name-only HEAD but # ac-187 is this a tag name. Will you please elaborate on the use of the above-mentioned command by you? Thanks in advance :)Cubitiere
git name-rev --name-only HEAD | cut -d / -f3 worked great for me in a detached state -- thanks!Eileneeilis
N
95

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}
Nestornestorian answered 4/4, 2012 at 15:20 Comment(1)
Too many slashes! :) sed -n 's/\* //p' does the trick. Although I tend toward the paranoid so I would anchor it with sed -n 's/^\* //p'.Warnke
H
91

write the following command in terminal :

git branch | grep \*

or

git branch --show-current 

or on Git 2.22 and above:

  git branch --show
Haden answered 1/3, 2022 at 11:59 Comment(0)
P
87

You can just type in command line (console) on Linux, in the repository directory:

$ git status

and you will see some text, among which something similar to:

...
On branch master
...

which means you are currently on master branch. If you are editing any file at that moment and it is located in the same local repository (local directory containing the files that are under Git version control management), you are editing file in this branch.

Peafowl answered 5/6, 2011 at 20:31 Comment(5)
Based on what you want to do, you can use git status and get only the first line of output with git status | head -1 which yields something like # On branch master. I'm sure version differences will needed to be accounted for as well.Dentalium
@JoshPinter: You can also use git status | grep 'On branch', which should have the same effect (should, does not mean it will if your version of Git displays it differently). Or git branch | grep '*', which will show the name of the branch with a star at the beginning of it.Peafowl
Yep, that works as well and might be more flexible. My final result for showing just the branch name in a dev Rails app was: <tick>git status | head -1<tick>.gsub('# On branch ', '')Dentalium
git status can take a long time to return a value if there are a lot of files being managed.Crump
Yeah, if you want to print the branch on a webpage, for example, git status may tank the whole page's generation time.Gestate
D
40
git symbolic-ref -q --short HEAD

I use this in scripts that need the current branch name. It will show you the current short symbolic reference to HEAD, which will be your current branch name.

Daleth answered 2/10, 2013 at 22:9 Comment(3)
Thanks, works great! - I'm also adding "-C path_to_folder" in my script with this.Salaam
This is a nice solution because with the -q option it returns an error code in the "detached HEAD" state but does not print anything to stderr.Virility
this is the only solution that worked for me on a fresh repo without any commitsEdrei
C
39

To get the current branch in git use,

git branch --show-current
Chare answered 26/10, 2021 at 6:53 Comment(4)
you have to finally edit this comment and remove the problemmatic dash, people copypaste answersDebbi
Hello @sych Sorry -- What is problemmatic with the dash in this command? This works fine copy-pasted on my machine (Linux, mint flavour, git version 2.25.1)Holusbolus
@Chare after you have edited it is fine :)Debbi
This is a duplicated answer from: stackoverflow.com/a/56501750Faustinafaustine
D
29
git branch | grep -e "^*" | cut -d' ' -f 2

will show only the branch name

Dael answered 14/6, 2016 at 13:8 Comment(2)
If your branch shows somethig like this "* (HEAD detached at SUM_BRANCH_01)", then try this "git branch | grep -e "^*" | cut -d' ' -f 5 | cut -d ')' -f 1"Balk
I just created this exact same script to get the current branch name. I figured it might help with diffs.Peroneus
G
29

git branch show current branch name only.

While git branch will show you all branches and highlight the current one with an asterisk, it can be too cumbersome when working with lots of branches.

To show only the branch you are currently on, use:

git rev-parse --abbrev-ref HEAD
Guest answered 25/5, 2018 at 5:33 Comment(3)
this is great for ci, and other build tools!Robbierobbin
best answer for using it in a scriptWether
@DylanNicholson git branch --contains sometimes lists more than one branch.Doyon
N
22

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!

Nippers answered 19/2, 2014 at 22:50 Comment(0)
H
22

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
Hasa answered 8/4, 2016 at 16:6 Comment(1)
Thanks for posting this, none of the other answers seemed to care about always producing something usable as an argument to git checkout.Reiner
A
22

A less noisy version for git status would do the trick

git status -bsuno

It prints out

## branch-name
Ash answered 21/3, 2018 at 23:55 Comment(2)
## develop...origin/developGravy
No way, it takes a few minutes to refresh index, then some time just hanging, and finally spits out several screens of file paths. Considering there's even no explanation on how it works and why it may be better than other suggestion, I'm giving it a -1Haematosis
T
20

Why not use git-aware shell prompt, which would tell you name of current branch? git status also helps.


How git-prompt.sh from contrib/ does it (git version 2.3.0), as defined in __git_ps1 helper function:

  1. First, there is special case if rebase in progress is detected. Git uses unnamed branch (detached HEAD) during the rebase process to make it atomic, and original branch is saved elsewhere.

  2. If the .git/HEAD file is a symbolic link (a very rare case, from the ancient history of Git), it uses git symbolic-ref HEAD 2>/dev/null

  3. Else, it reads .git/HEAD file. Next steps depends on its contents:

    • If this file doesn't exist, then there is no current branch. This usually happens if the repository is bare.

    • If it starts with 'ref: ' prefix, then .git/HEAD is symref (symbolic reference), and we are on normal branch. Strip this prefix to get full name, and strip refs/heads/ to get short name of the current branch:

      b="${head#ref: }"
      # ...
      b=${b##refs/heads/}
      
    • If it doesn't start with 'ref: ', then it is detached HEAD (anonymous branch), pointing directly to some commit. Use git describe ... to write the current commit in human-readable form.

I hope that helps.

Thigmotropism answered 5/6, 2011 at 22:25 Comment(4)
And if you are developing a git-aware shell prompt, which of the answers here should you use? Turtles all the way down.Autonomic
@tripleee: Borrow ideas from github.com/git/git/blob/master/contrib/completion/git-prompt.shDemount
Which for the record appears to be doing git describe --contains --all HEAD which I don't currently see elsewhere on this page. As I'm sure you know, link-only answers are not recommended on StackOverflow.Autonomic
@tripleee: I have added an explanation how git-prompt.sh (aka __git_ps1) does it...Demount
C
20

I would try one of the following:

1.> git symbolic-ref --short HEAD

git symbolic-ref --short HEAD
>>> sid-dev

2.> git branch --show-current

git branch --show-current
>>> sid-dev

3.> git name-rev –name-only HEAD

git name-rev –name-only HEAD
>>> HEAD sid-dev

Notes:

1.> git symbolic-ref --short HEAD displays the short symbolic reference to the current branch’s HEAD. This is the current branch name.

2.> git branch --show-current is also a simple and efficient way to print the current branch name.

3.> git name-rev –name-only HEAD gives the symbolic name for HEAD revision of the current branch

4.> In the above examples, sid-dev is the name of my branch.

Cockneyfy answered 10/10, 2021 at 22:1 Comment(0)
D
20

There is various way to check the current branch of Git but I prefer :

git branch --show

Even git branch also shows the current branch name along with all existing branch name list.

Dimorphous answered 17/12, 2021 at 8:38 Comment(1)
There is no --show flag; apparently this works because it's unambiguous abbreviation of --show-current. E.g. --sho and --show-cu also work...Wellmannered
P
18
#!/bin/bash
function git.branch {
  br=`git branch | grep "*"`
  echo ${br/* /}
}
git.branch
Prasad answered 23/1, 2012 at 17:11 Comment(0)
S
18

you can use git bash on the working directory command is as follow

git status -b

it will tell you on which branch you are on there are many commands which are useful some of them are

-s

--short Give the output in the short-format.

-b --branch Show the branch and tracking info even in short-format.

--porcelain[=] Give the output in an easy-to-parse format for scripts. This is similar to the short output, but will remain stable across Git versions and regardless of user configuration. See below for details.

The version parameter is used to specify the format version. This is optional and defaults to the original version v1 format.

--long Give the output in the long-format. This is the default.

-v --verbose In addition to the names of files that have been changed, also show the textual changes that are staged to be committed (i.e., like the output of git diff --cached). If -v is specified twice, then also show the changes in the working tree that have not yet been staged (i.e., like the output of git diff).

Saffian answered 8/12, 2016 at 12:19 Comment(0)
M
17
git status 

will also give the branch name along with changes.

e.g.

>git status
On branch master // <-- branch name here
.....
Misconstruction answered 13/1, 2018 at 2:15 Comment(0)
A
16

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

Arawn answered 11/3, 2014 at 20:41 Comment(0)
G
14

I recommend using any of these two commands.

git branch | grep -e "^*" | cut -d' ' -f 2

OR

git status | sed -n 1p | cut -d' ' -f 3

OR (more verbose)

git status -uno -bs| cut -d'#' -f 3 | cut -d . -f 1| sed -e 's/^[ \t]//1'| sed -n 1p

Gusella answered 22/2, 2018 at 16:12 Comment(0)
P
12

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

Petitionary answered 9/8, 2012 at 16:10 Comment(1)
With versioning annotations enabled, then all you need to do is hover your mouse over the Project (or File, or Favorite) folder to see the current branch.Unesco
G
12

What about this?

{ git symbolic-ref HEAD 2> /dev/null || git rev-parse --short HEAD 2> /dev/null } | sed "s#refs/heads/##"
Goings answered 11/4, 2013 at 17:29 Comment(4)
Much better answer because it handles the detached HEAD case well.Vindictive
Seems like you should be using () not { } to wrap the git commandsVindictive
@Vindictive There's no need to spawn a separate subshell for this, as ( ) would do. { } is fine, except you do need to add a ; or newline before the }. Actually, you could just leave off the { } entirely unless you needed to group the commands.Loathing
Doesn't the symbolic-ref part also need --short to avoid prefixing the branchname with refs/heads/?Recession
H
12

You can permanently set up your bash output to show your git-branch name. It is very handy when you work with different branches, no need to type $ git status all the time. Github repo git-aware-prompt .

Open your terminal (ctrl-alt-t) and enter the commands

mkdir ~/.bash
cd ~/.bash
git clone git://github.com/jimeh/git-aware-prompt.git

Edit your .bashrc with sudo nano ~/.bashrc command (for Ubuntu) and add the following to the top:

export GITAWAREPROMPT=~/.bash/git-aware-prompt
source "${GITAWAREPROMPT}/main.sh"

Then paste the code

export PS1="\${debian_chroot:+(\$debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[$txtcyn\]\$git_branch\[$txtred\]\$git_dirty\[$txtrst\]\$ "

at the end of the same file you pasted the installation code into earlier. This will give you the colorized output:enter image description here

Heterochromosome answered 14/10, 2016 at 16:13 Comment(0)
U
12

The following shell command tells you the branch that you are currently in.

git branch | grep ^\*

When you don't want to type that long command every time you want to know the branch and you are using Bash, give the command a short alias, for example alias cb, like so.

alias cb='git branch | grep ^\*'

When you are in branch master and your prompt is $, you will get * master as follows.

$ cb
* master
Unfortunate answered 16/11, 2016 at 21:19 Comment(6)
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From ReviewClassic
Why do you think so?Unfortunate
you should comment and describe your post for the OP, in that way it will be easier to understand your post.Classic
Makes perfect sense.Unfortunate
if you use zsh you'll need to wrap the grep regex in single quotes: git branch | grep '^\*'Ferrol
Also if you want the plain branch name without the * (e.g. for scripts) you can pipe through awk: git branch | grep ^\* | awk '{print $2}'Ferrol
K
11

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.

Kokura answered 3/5, 2016 at 17:47 Comment(0)
H
11

Returns either branch name or SHA1 when on detached head:

git rev-parse --abbrev-ref HEAD | grep -v ^HEAD$ || git rev-parse HEAD

This is a short version of @dmaestro12's answer and without tag support.

Hairdresser answered 17/10, 2017 at 20:30 Comment(1)
better: git symbolic-ref --quiet --short HEAD || git rev-parse --short HEADGausman
S
9

A simple hack could be

git branch|grep "*"

Output:

* <current branch>

EDIT:

Another way to know current branch

git status|head -1
On branch <current branch name>
Secularism answered 3/2, 2022 at 17:55 Comment(0)
W
8

if you run in Jenkins, you can use GIT_BRANCH variable as appears here: https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin

The git plugin sets several environment variables you can use in your scripts:

  1. GIT_COMMIT - SHA of the current

  2. GIT_BRANCH - Name of the branch currently being used, e.g. "master" or "origin/foo"

  3. GIT_PREVIOUS_COMMIT - SHA of the previous built commit from the same branch (the current SHA on first build in branch)

  4. GIT_URL - Repository remote URL

  5. GIT_URL_N - Repository remote URLs when there are more than 1 remotes, e.g. GIT_URL_1, GIT_URL_2

  6. GIT_AUTHOR_EMAIL - Committer/Author Email

  7. GIT_COMMITTER_EMAIL - Committer/Author Email

Wray answered 11/3, 2014 at 9:8 Comment(0)
S
8

If you really want the last branch/tag checked out in detached HEAD state as well.

git reflog HEAD | grep 'checkout:' | head -1 | rev | cut -d' ' -f1 | rev

Update This is nicer if you have and aren't scared of awk.

git reflog HEAD | grep 'checkout:' | head -1 | awk '{print $NF}'
Sari answered 20/8, 2014 at 5:40 Comment(3)
the rev | cut -d' ' -f1| rev can be simplified with awk '{print $NF}'Farmstead
While this isn't foolproof either, since you can checkout a particular revision by hash, so that the reflog just shows checkout: moving from ba7571b7fc5b8f31b8d0625821269afaa655577e to f68be8cf7bea917a5a0562b619e50368de0068a9 it is still a useful trick that might help to disambiguate some cases.Wynd
Further shorten to git reflog | awk '$3=="checkout:" {print $NF; exit}'Wheal
R
6

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"
Ribose answered 20/8, 2014 at 22:41 Comment(1)
head -1 would the usual wayVermicelli
V
6

Use git branch --contains HEAD | tail -1 it also works for "detached HEAD" state.

Vachell answered 17/1, 2019 at 1:37 Comment(0)
K
5

Add it to PS1 using Mac :

PS1='\W@\u >`[ -d .git ] && git branch | grep  ^*|cut -d" " -f2`> $ '

Before running the command above :

enter image description here

After running that command :

enter image description here

Dont worry, if it is not GIT repository , it will not display error because of [-d .git] which checks if .git folder exists or not.

Kenway answered 31/10, 2016 at 6:56 Comment(0)
B
5

I wanted a single line that I could parse in a Windows CMD shell (most of the answers here use unix commands). Most of the answers also had problems with sparse checkouts and detached heads.

git branch

gives a list of branches that are available in the working copy, with an * in front of the checked out one. This is good for a quick look but not for parsing.

git rev-parse --abbrev-ref HEAD

just showed HEAD as the branch when using it on a detached HEAD checkout. Similarly when using

git symbolic-ref HEAD

I got fatal: ref HEAD is not a symbolic ref when using a detached head that was from a tag.

git describe --contains --all HEAD

seems to work most of the time and was close to what I want, but with some repos just returned a blank line.

git status

works except it lists all differences in the repo which makes it a bit difficult to parse.

I ended up settling on the following;

git status |findstr/n ^^|findstr "^[1]: ^[0]:"

This gives output like the following;

1:HEAD detached at 2.30.20

or

1:On branch master

Bahia answered 7/3, 2023 at 20:21 Comment(0)
S
4

In case your CI server does not have environment variable with branch name and you have a dockerized build without git binary inside of container, you can just use:

cat .git/HEAD | awk -F '/' '{print $NF}'

Stereotaxis answered 7/2, 2020 at 13:44 Comment(3)
Unfortunately, this can't be consistently relied on as the CI server might do a headless checkout so the file .git/HEAD will only contain the SHA of the corresponding commit.Stuckey
along with the comment by @MattClegg, using cat is superfluous. Simply doing awk -F '/' '{print $NF}' $PATH/to/.git/HEADAttenuator
It will also fail if your branch is named feature/foo, as you will only get foo.Underwrite
U
4

I've been battling with CircleCI and git tags and this is what I ended up with:

if [[ -n $(git branch --show-current) ]]; then
    git branch --show-current
else
    git branch -a --contains $(git rev-parse --short HEAD) \
    | sed '/HEAD/d' \
    | sed 's/remotes\/origin\///g' \
    | sed 's/\*//g' | sed 's/ *//g' \
    | awk '!_[$0]++'
fi

While it's a bit ugly, it does

  • work for regular commits: it just uses git's --show-current flag and if that worked we need to look no further; both locally and on the CI container
  • work for tags: when the head is detached, it will get the remote branch name instead.

Caveats:

  • This works fine as long as the tagged commits only appear on one branch. So if you're normally merging to say dev and from there via staging to production, the original commit from dev will appear on all three branches, thereby breaking this code. But as long as you only ever tag the merge/PR commit
  • This requires to run git fetch -a to be run beforehand since the CI will only check out the default branch and the tagged commit so if the correct branch is neither of these it won't work

Some more explanation:

  • I wanted to get the branch name, even when a CI build was triggered by a tag. In that case, the CircleCI pipeline.git.branch variable is not set nor can I easily get the branch name from git as the head is detached (as pointed out in many of the other questions). This means grepping the current branch (using the * prefix) doesn't work either as on the CI, the current branch will be the detached head one.
  • The idea is to get all branches that include this commit (including remote ones); then remove the detached head result, get rid of all bits that aren't the actual branch name and de-duplicate
Underpants answered 24/1, 2022 at 15:49 Comment(0)
T
3
git branch | grep "*" | sed "s/* //" | awk '{printf $0}' | pbcopy

To directly copy the result to the pasteboard. Thanks to @olivier-refalo for the start…

Topliffe answered 26/4, 2013 at 19:55 Comment(3)
Ugh. grep | sed | awk can usually be easily refactored to just one Awk script. (What's the point of printf $0 anyway? To trim the final newline? tr -d '\n' does that much better.) Also, grep "*" is technically a syntax error. Anyway, git branch | awk '/\*/ { gsub(/\* /,""); printf $0 } | pbcopy is a simple refactoring of your script.Autonomic
... and git branch | awk '/^\*/ { printf $2 }' (as already posted above) is much better.Autonomic
sed is cheaper than awk: git branch | sed -ne '/^\* / { s///; p; q }'Induration
P
3

On Shell, You can do the following

git branch | grep '*'
Palaeogene answered 12/1, 2022 at 4:46 Comment(0)
L
3

Just the name of the current branch if on a branch, but if detached then print the current commit id:

git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --short HEAD 

The first part will return an error if detached, and the second part will always print the current commit id.

Lighthouse answered 12/8, 2022 at 15:32 Comment(0)
L
2

Using earlier ideas; assuming sha1 is 40 characters; and chasing references (yea, should delete the debug print lines :-):

git reflog | awk '
$3 == "checkout:" && (sha == "" || sha == $1 ) {
  from=$(NF - 2)
  to=$NF
  print from, to, length(from) > "/dev/stderr"
  if (length(from) != 40) { print from ; exit; }
  sha=substr(from, 1, 7)
  print sha > "/dev/stderr"
}
'

gives the raw output:

$ git status
HEAD detached at 147049c
[...]
$ ./gime-branch.sh
a47be8d2167641088b66bf8f5c2bf7d3da0c642c HEAD^ 40
a47be8d
master HEAD^ 6
master
Lampion answered 24/8, 2016 at 16:20 Comment(0)
S
2
git branch -l

This will list all your local branches with your current branch stared and printed in green enter image description here

Shattuck answered 16/8, 2022 at 19:56 Comment(0)
C
2

git branch -a | grep -i "*"

Cuneo answered 28/4, 2023 at 5:48 Comment(0)
M
2

Short answer:

git branch --show-current

To put it in a variable in a bash script for example:

@current_branch=$$(git branch --show-current); 
Marinemarinelli answered 18/3 at 10:32 Comment(2)
This answer duplicates information that is already in the accepted answer (with the green checkmark).Begin
Thanks @Begin for the note, I modified the answer and put it into a more useful context.Marinemarinelli
C
1

Simply, add following lines to your ~/.bash_profile:

branch_show() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(branch_show)\[\033[00m\] $ "

In this way, you can have the current branch name in Terminal

Courtesy of Coderwall.com

Chloride answered 28/12, 2017 at 16:55 Comment(0)
P
1

You can do this with a single grep instruction, using Perl mode and \K to reset the match buffer, so you get only the branch name.

$ git branch | grep -oP "^\*\s+\K\S+$"
master
Procne answered 4/5, 2019 at 21:4 Comment(1)
absolutely correctKeitel
E
1
git log

This command will display the commits list with the current branch name at the top.

Embrace answered 4/5, 2022 at 19:27 Comment(1)
This is a very simple solution. I'm surprised that no one voted it up before. Way more complex answers have been provided beforeWessels
B
0

You can also see name of current branch in your .git directory of current project.

type command in terminal: open .git/HEAD output file contains the name of current branch ref: refs/heads/{current_working_branch}

Babushka answered 20/11, 2019 at 6:17 Comment(1)
That is correct indeed, if your HEAD is not detached (meaning you have checked out a branch, not directly a commit or tag). If your HEAD is detached, then .git/HEAD would contain a SHA1, not a branch name.Bystander
M
0

Tried above answers but there is always 'detached HEAD' issue that comes with several commands. This ones works for me so far. It will correctly output the branch name even if the branch name contains / in the name

git describe --all --exact-match | sed 's/heads\///'
Maggio answered 11/9, 2023 at 15:4 Comment(1)
This command outputs the branch name which points to the commit that I'm on while in “detached HEAD” state. I expected it to output nothing since I'm not on any branch.Simpson
L
-1

I know this has been answered already, but in the most recent version of Git the command git branch opens a list of your branches in some kind of prompt that you have to quit out of. Which annoys me to no end!

Here's my fix: Open your bash profile and type this in:

#!/bin/bash
git() {
  if [[ $@ == "branch" ]] then
    command git branch -a | grep -v 'remotes'
  else
    command git "$@"
  fi
}

Now open Terminal and test it out by typing the following commands in a git repo:

source ~/.zshrc
git branch 

And voila! A list of your local branches is printed out in your terminal.

The code you're writing to your bashrc file overwrites the default function for git branch and replaces it with a much longer command that lists all local branches via the -a argument. Then we grep out the extra not needed business and print it out. If you exclude the grep command you'll still get the annoying prompt. If you're not familiar with writing bash commands checkout this explanation: About .bash_profile, .bashrc, and where should alias be written in?

Longfaced answered 14/6, 2018 at 18:51 Comment(1)
This has a couple problematic assumptions. Firstly, the behavior seems to imply a config of --all which always display remotes, and is not the default. Secondly, the pagination prompt is triggered by a long list, so the above grep filter only benefits until the number of local branches is longer than screen height.Amadis

© 2022 - 2024 — McMap. All rights reserved.