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

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


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 HEADbranch_name=${branch_name##refs/heads/}

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)branch_name=${branch_name##refs/heads/}branch_name=${branch_name:-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.


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.


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