How to programmatically determine the current checked out Git branch [duplicate] – Dev

The best answers to the question “How to programmatically determine the current checked out Git branch [duplicate]” in the category Dev.


In a Unix or GNU scripting environment (e.g. a Linux distro, Cygwin, OSX), what is the best way to determine which Git branch is currently checked out in a working directory?

One use of this technique would be automatically labeling a release (like svnversion would do with Subversion).

Please also see my related question: How to programmatically determine whether a Git checkout is a tag, and if so what is the tag name?


Does anyone see anything wrong with just asking Git to describe the branch you are on?

git rev-parse --symbolic-full-name --abbrev-ref HEAD

That can be used within $() and passed easily in Bash, Powershell, Perl, etc. It isn’t fooled if you have several branches on the commit you are on, and if you currently aren’t on a branch, it simply replies with “HEAD”.

Alternatively, you can use

git symbolic-ref --short -q HEAD

Which will give you the same output, but it won’t return anything at all if you are detached. This one is useful if you want an error when detached though, just remove the -q.


The correct solution is to take a peek at contrib/completions/git-completion.bash does that for bash prompt in __git_ps1. Removing all extras like selecting how to describe detached HEAD situation, i.e. when we are on unnamed branch, it is:

branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)"     # detached HEAD


git symbolic-ref is used to extract fully qualified branch name from symbolic reference; we use it for HEAD, which is currently checked out branch.

Alternate solution could be:

branch_name=$(git symbolic-ref -q HEAD)

where in last line we deal with the detached HEAD situation, using simply “HEAD” to denote such situation.

Added 11-06-2013

Junio C. Hamano (git maintainer) blog post, Checking the current branch programatically, from June 10, 2013 explains whys (and hows) in more detail.


From this answer: :

$ git rev-parse --abbrev-ref HEAD

Apparently works with Git 1.6.3 or newer.


you can use
git name-rev --name-only HEAD