How to programmatically determine the current checked out Git branch
From this answer: https://stackoverflow.com/a/1418022/605356 :
$ git rev-parse --abbrev-ref HEAD
master
Apparently works with Git 1.6.3 or newer.
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
branch_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.
you can use
git name-rev --name-only HEAD