3033

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 sure when I am editing a file in NetBeans or Notepad++, whether it's tied to the master or another branch.

There's no problem with git in bash, it tells me what I'm doing.

Kay V
  • 1,917
  • 12
  • 14
mike628
  • 36,755
  • 16
  • 37
  • 51
  • 13
    Let your IDE display the file `.git/HEAD`, possibly in a parent directory – Tino Feb 04 '12 at 12:37
  • 108
    http://stackoverflow.com/questions/1417957/show-just-the-current-branch-in-git $ git rev-parse --abbrev-ref HEAD – fantastory Feb 28 '14 at 10:51
  • 2
    possible duplicate of [How to programmatically determine the current checked out Git branch](http://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch) – tripleee Jun 10 '15 at 10:20
  • 2
    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. – idclaar Sep 30 '15 at 00:08
  • 8
    Possible duplicate of [Show just the current branch in Git](http://stackoverflow.com/questions/1417957/show-just-the-current-branch-in-git) – techraf Jan 18 '17 at 03:44
  • 17
    With Git 2.22 (Q2 2019), you will have a simpler approach: `git branch --show-current`. See [my answer here](https://stackoverflow.com/a/55088865/6309). – VonC Mar 10 '19 at 14:50
  • Interesting curiosity; git was created in 2005 and 14 years later it is now possible to show current branch… Mercurial was also created in 2005 and 1 year later it was possible to show current branch (from [changelog](https://www.mercurial-scm.org/wiki/WhatsNew/Archive#Version_0.9.2_-_2006-12-10) of version 0.9.2 – _new branch and branches commands for managing named branches_). – Piotr Dobrogost Dec 20 '20 at 13:20

38 Answers38

4747

To display the current branch you're on, without the other branches listed, you can do the following:

git rev-parse --abbrev-ref HEAD

Reference:

Oren Milman
  • 414
  • 4
  • 14
Jistanidiot
  • 47,967
  • 3
  • 15
  • 27
3052
git branch

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

If you want to retrieve only the name of the branch you are on, you can do:

git rev-parse --abbrev-ref HEAD

or with Git 2.22 and above:

git branch --show-current
smbear
  • 948
  • 9
  • 15
roberttdev
  • 32,556
  • 2
  • 18
  • 23
  • 1
    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. – mike628 Jun 05 '11 at 20:30
  • @mike628 Actually they are helping you except you want something accessible through GUI. Correct? – Tadeck Jun 05 '11 at 20:34
  • 2
    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). – roberttdev Jun 05 '11 at 20:51
  • 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? – Honey Aug 29 '16 at 20:29
  • 4
    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. – Marcus Junius Brutus Sep 11 '16 at 20:13
  • 3
    downvote, we want only the current branch as stdout, not all the branches – Alexander Mills Nov 02 '16 at 00:00
  • I've asked the same type of question **[here](http://stackoverflow.com/questions/41044807/retrieving-git-branch-name-in-prompt-or-android-gradle-on-jenkins-it-returns-he)**, using a similar approach as possible solution. However, I cannot use the 'grep \*' (based on comment by @fboes) in gradle code. Advice anyone? – P Kuijpers Dec 20 '16 at 15:43
  • Thanks @fboes I was looking for the same option. – yohannan_sobin Apr 21 '17 at 05:39
  • while this answer gives you more detail, it requires a complex script to parse thru. @jistanidiot provided a much more direct, and concise, answer – chris.nesbit1 Jul 27 '17 at 17:37
  • `gitbranch="$( git branch | grep \* )"` `currentbranch="$([[ "${gitbranch}" == "* (HEAD"* ]] && echo "${gitbranch}" | cut -d ' ' -f5 | cut -d ')' -f1 || echo "${gitbranch}" | cut -d ' ' -f2-)"` – codekandis Jan 23 '18 at 13:04
  • 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)` fails – Frédéric Camblor Sep 06 '18 at 08:08
  • This is v. slow. The code in the question given here is much faster: https://stackoverflow.com/questions/1417957/show-just-the-current-branch-in-git/1418022 – Colm Bhandal Oct 01 '18 at 16:37
  • I agree with @boobiq's comment. It can also be done with `git branch | grep \* | cut -c3-`. This helps with "(no branch)" branch. – dlink Feb 14 '19 at 18:14
  • Using porcelain commands in scripts is *never* the right approach: -1. – Voo May 03 '19 at 09:49
  • using awk, `git branch | awk '{if ($1 == "*") print $2}'` – viggy28 Nov 13 '19 at 17:29
  • This solution doesn't work after `git checkout --orphan branch` – AndrewHarvey Jan 27 '20 at 06:59
  • 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. – Schneems Sep 10 '20 at 15:23
  • I used `git rev-parse --abbrev-ref HEAD` on script, and it became perfect – Sham Fiorin Feb 17 '21 at 17:54
  • 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. – eric.frederich Mar 17 '21 at 17:27
553

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

Community
  • 1
  • 1
Wernight
  • 32,087
  • 22
  • 110
  • 128
  • 9
    As all other answers, this doesn't work when you are in a 'detached HEAD' state – Carlos Campderrós Jan 30 '13 at 10:09
  • 55
    @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. – Flimm Jan 07 '14 at 14:07
  • 2
    this makes problems in empty git repositories when there is no HEAD – Arne Mar 31 '15 at 20:57
  • 11
    With git version 2.4.4 `git rev-parse --abbrev-ref HEAD` shows `HEAD` when you’re on detached head. – peterhil Jul 11 '15 at 13:37
  • 1
    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. – Bernard Jan 15 '16 at 06:12
  • This is also whats used in git-prompt.sh (the branch name that will be displayed in your bash prompt if enabled). – Zitrax Apr 19 '16 at 10:59
  • 1
    This works after `git checkout --orphan branch` unlike the accepted answer. – AndrewHarvey Jan 27 '20 at 07:00
291

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)

Delgan
  • 14,714
  • 6
  • 77
  • 119
Stefaan
  • 4,268
  • 3
  • 20
  • 16
  • 6
    In summary, none seem to do quite what I would by hand. – bukzor Feb 04 '15 at 19:31
  • 7
    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. – Alex Dupuy May 18 '15 at 09:31
  • 1
    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. – Alex Dupuy May 20 '15 at 07:31
  • Actually, I need to use `git branch --no-color` to make sure that the filename is free of annoying terminal escape codes. – Alex Dupuy May 20 '15 at 07:48
  • 2
    This has been really helpful to me more than once, thanks for being so thorough! – Alice Purcell Nov 03 '16 at 12:37
  • "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. – Beni Cherniavsky-Paskin Apr 22 '20 at 18:52
199

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.

nh2
  • 22,055
  • 11
  • 64
  • 113
Max
  • 11,136
  • 15
  • 65
  • 92
  • 2
    Yes, I mentioned that last March in the comments of that page: https://stackoverflow.com/questions/6245570/how-to-get-the-current-branch-name-in-git/56501750#comment96922502_6245570. And in https://stackoverflow.com/a/55088865/6309. – VonC Jun 07 '19 at 22:37
  • 6
    At least mention this does **not** work in detached HEAD state. Just lost hours getting git 2.22 to compile for nothing ... – David Deprost Dec 16 '19 at 04:02
  • Available since Git version 2.22 : https://github.com/git/git/blob/master/Documentation/RelNotes/2.22.0.txt#L32 – Lenormju Jul 01 '20 at 08:26
  • it does not show the branch name. All it is showing is main – Karen Goh May 06 '21 at 04:07
  • @KarenGoh It will show main, when you are currently on a branch called `main`. – Max May 06 '21 at 07:28
  • It doesn't show the branch name. Only when I do git remote -v then it will show the name. – Karen Goh May 06 '21 at 14:55
  • That is strange. Are you sure that you are running atleast 2.22? – Max May 06 '21 at 15:07
137

One more alternative:

git name-rev --name-only HEAD
Filip Spiridonov
  • 24,912
  • 4
  • 22
  • 29
  • it also can be retrieved with `echo ${$(git symbolic-ref --quiet HEAD)#refs/heads/}` – Antoine Mar 16 '16 at 14:24
  • 13
    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. – Orest Hera Apr 06 '16 at 09:05
  • 1
    `git checkout master && git name-rev --name-only HEAD # ac-187` It does not work as expected – Alexander Abashkin May 19 '16 at 13:41
  • 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. – Ishaan Sejwal Nov 12 '16 at 17:16
  • 5
    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. – Mig82 Jun 19 '17 at 11:53
  • And for windows users add `| clip` to put it on the clipboard. – dudeNumber4 Sep 06 '17 at 20:34
  • 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. – AnneTheAgile Jul 11 '18 at 22:02
  • 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. – Martin Maat Oct 11 '18 at 07:50
  • @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 :) – Chandra Shekhar Paatni Nov 12 '19 at 04:42
93

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}
Olivier Refalo
  • 46,213
  • 20
  • 84
  • 114
  • 9
    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'`. – Mark Reed Aug 04 '14 at 14:45
68

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.

Tadeck
  • 117,059
  • 25
  • 140
  • 191
  • 2
    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. – Joshua Pinter Dec 31 '11 at 20:43
  • @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. – Tadeck Jan 01 '12 at 00:38
  • 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: `git status | head -1.gsub('# On branch ', '')` – Joshua Pinter Jan 04 '12 at 19:45
  • 3
    `git status` can take a long time to return a value if there are a lot of files being managed. – the Tin Man May 09 '16 at 23:53
  • Yeah, if you want to print the branch on a webpage, for example, `git status` may tank the whole page's generation time. – Artem Russakovskii Jul 03 '19 at 18:06
38
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.

Kousha
  • 1,497
  • 14
  • 18
  • 1
    Thanks, works great! - I'm also adding "-C path_to_folder" in my script with this. – Tony Aug 06 '15 at 10:02
  • 1
    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. – hallidave Mar 31 '19 at 16:26
  • this is the only solution that worked for me on a fresh repo without any commits – kundasaba Apr 14 '19 at 11:55
27
git branch | grep -e "^*" | cut -d' ' -f 2

will show only the branch name

ungalcrys
  • 4,558
  • 2
  • 35
  • 22
  • 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" – Dylan Kapp Aug 04 '16 at 21:42
  • I just created this exact same script to get the current branch name. I figured it might help with diffs. – tggagne Aug 09 '16 at 04:57
26

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
Lawrence Paje
  • 301
  • 3
  • 4
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!

Community
  • 1
  • 1
Silas Barta
  • 393
  • 2
  • 9
19

A less noisy version for git status would do the trick

git status -bsuno

It prints out

## branch-name
dgolovin
  • 1,314
  • 10
  • 22
19

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.

Jakub Narębski
  • 268,805
  • 58
  • 209
  • 228
  • 3
    And if you are developing a git-aware shell prompt, which of the answers here should you use? Turtles all the way down. – tripleee Feb 18 '15 at 11:52
  • 1
    @tripleee: Borrow ideas from https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh – Jakub Narębski Feb 18 '15 at 12:00
  • 4
    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. – tripleee Feb 18 '15 at 12:11
  • 2
    @tripleee: I have added an explanation how `git-prompt.sh` (aka `__git_ps1`) does it... – Jakub Narębski Feb 20 '15 at 17:51
19
#!/bin/bash
function git.branch {
  br=`git branch | grep "*"`
  echo ${br/* /}
}
git.branch
Dziamid
  • 10,081
  • 11
  • 62
  • 100
17

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
dmaestro12
  • 833
  • 7
  • 15
  • 1
    Thanks for posting this, none of the other answers seemed to care about always producing something usable as an argument to `git checkout`. – zwol Dec 09 '18 at 16:43
15

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).

Prateek Gangwal
  • 794
  • 6
  • 11
15
git status 

will also give the branch name along with changes.

e.g.

>git status
On branch master // <-- branch name here
.....
Paul Rooney
  • 17,518
  • 8
  • 35
  • 57
Satheesh Kumar
  • 727
  • 6
  • 28
14

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

karthikr
  • 87,486
  • 24
  • 182
  • 182
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

jackotonye
  • 2,859
  • 18
  • 28
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

Saroj
  • 1,018
  • 11
  • 16
  • 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. – idclaar Sep 30 '15 at 00:06
12

What about this?

{ git symbolic-ref HEAD 2> /dev/null || git rev-parse --short HEAD 2> /dev/null } | sed "s#refs/heads/##"
ShogunPanda
  • 1,046
  • 1
  • 10
  • 11
  • 1
    Much better answer because it handles the detached HEAD case well. – Pat Jun 13 '13 at 19:11
  • 2
    Seems like you should be using () not { } to wrap the git commands – Pat Jun 13 '13 at 19:45
  • @Pat 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. – aij Feb 28 '15 at 15:51
  • 1
    Doesn't the `symbolic-ref` part also need `--short` to avoid prefixing the branchname with `refs/heads/`? – rjp Jan 02 '18 at 15:41
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.

Diego Pino
  • 9,928
  • 1
  • 48
  • 52
11

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

Kirill Zhuravlov
  • 364
  • 6
  • 20
11

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
mrrusof
  • 342
  • 2
  • 8
9

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.

user
  • 16,328
  • 6
  • 89
  • 89
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}'
Ryan
  • 3,607
  • 1
  • 23
  • 33
  • the `rev | cut -d' ' -f1| rev` can be simplified with `awk '{print $NF}'` – Steve Buzonas Jan 18 '15 at 02:03
  • 1
    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. – Alex Dupuy May 18 '15 at 11:48
  • 2
    Further shorten to `git reflog | awk '$3=="checkout:" {print $NF; exit}'` – jthill Mar 06 '16 at 02:06
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"
skippy
  • 227
  • 3
  • 11
5

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:

GIT_COMMIT - SHA of the current

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

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

GIT_URL - Repository remote URL

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

GIT_AUTHOR_EMAIL - Committer/Author Email

GIT_COMMITTER_EMAIL - Committer/Author Email

user3405314
  • 59
  • 1
  • 3
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.

Abdennour TOUMI
  • 64,884
  • 28
  • 201
  • 207
4

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

glisu
  • 822
  • 5
  • 19
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…

SushiGrass Jacob
  • 19,278
  • 1
  • 23
  • 39
  • 1
    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. – tripleee Oct 07 '14 at 04:41
  • ... and `git branch | awk '/^\*/ { printf $2 }'` (as already posted above) is much better. – tripleee Feb 18 '15 at 11:54
  • 1
    `sed` is cheaper than `awk`: `git branch | sed -ne '/^\* / { s///; p; q }'` – musiphil Jun 18 '15 at 07:33
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
cagney
  • 408
  • 3
  • 11
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

Shayan Amani
  • 4,216
  • 1
  • 31
  • 35
1

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}'

Kirill
  • 3,834
  • 2
  • 28
  • 51
  • 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. – Matt Clegg Jun 04 '20 at 10:18
  • 2
    along with the comment by @MattClegg, using `cat` is superfluous. Simply doing `awk -F '/' '{print $NF}' $PATH/to/.git/HEAD` – Jim Aug 13 '20 at 21:56
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}

  • 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. – VonC Nov 20 '19 at 07:05
-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?

okTalk
  • 862
  • 1
  • 8
  • 11
  • 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. – MarkHu Sep 05 '19 at 17:51
-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
Joseph Lust
  • 17,180
  • 7
  • 70
  • 72