[git] How to get the current branch name in Git?

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.

This question is related to git branch git-branch

The answer is


One more alternative:

git name-rev --name-only HEAD

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

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

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

will show only the branch name


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

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


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.


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:


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


What about this?

{ git symbolic-ref HEAD 2> /dev/null || git rev-parse --short HEAD 2> /dev/null } | sed "s#refs/heads/##"

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"

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


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


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.


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


#!/bin/bash
function git.branch {
  br=`git branch | grep "*"`
  echo ${br/* /}
}
git.branch

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}

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.


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.


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}


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

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


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


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


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?


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


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.


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.


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!


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

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

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


git status 

will also give the branch name along with changes.

e.g.

>git status
On branch master // <-- branch name here
.....

A less noisy version for git status would do the trick

git status -bsuno

It prints out

## branch-name

git branch | grep "*" | sed "s/* //" | awk '{printf $0}' | pbcopy

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


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)


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.


Examples related to git

Does the target directory for a git clone have to match the repo name? Git fatal: protocol 'https' is not supported Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) git clone: Authentication failed for <URL> destination path already exists and is not an empty directory SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 GitLab remote: HTTP Basic: Access denied and fatal Authentication How can I switch to another branch in git? VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio?

Examples related to branch

Get git branch name in Jenkins Pipeline/Jenkinsfile Why do I have to "git push --set-upstream origin <branch>"? Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.? When does Git refresh the list of remote branches? Fix GitLab error: "you are not allowed to push code to protected branches on this project"? Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository." Git: Merge a Remote branch locally git pull from master into the development branch Depend on a branch or tag using a git URL in a package.json? How can I copy the content of a branch to a new local branch?

Examples related to git-branch

How do I rename both a Git local and remote branch name? How do I create a master branch in a bare Git repository? git switch branch without discarding local changes Git: Merge a Remote branch locally Why call git branch --unset-upstream to fixup? Create a remote branch on GitHub How can I display the current branch and folder path in terminal? Git merge master into feature branch Delete branches in Bitbucket Creating a new empty branch for a new project