Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the current git branch in detached HEAD state

I can find the current git branch name by doing either of these:

git branch | awk '/^\*/ { print $2 }' git describe --contains --all HEAD 

But when in a detached HEAD state, such as in the post build phase in a Jenkins maven build (or in a Travis git fetch), these commands doesn't work.

My current working solution is this:

git show-ref | grep $(git log --pretty=%h -1) | sed 's|.*/\(.*\)|\1|' | sort -u | grep -v HEAD 

It displays any branch name that has the last commit on its HEAD tip. This works fine, but I feel that someone with stronger git-fu might have a prettier solution?

like image 356
neu242 Avatar asked May 19 '11 13:05

neu242


People also ask

How do I know which branch is my head?

You can view your repository's heads in the path . git/refs/heads/ . In this path you will find one file for each branch, and the content in each file will be the commit ID of the tip (most recent commit) of that branch.

Why is my branch in detached head state?

If you check out to the origin (main) branch, which is read-only, you will be in the detached HEAD state. Some other scenarios can cause a detached HEAD as well. For example, checking out to a specific tag name or adding ^0 on any given branch causes the detached HEAD state.


1 Answers

A more porcelain way:

git log -n 1 --pretty=%d HEAD  # or equivalently: git show -s --pretty=%d HEAD 

The refs will be listed in the format (HEAD, master) - you'll have to parse it a little bit if you intend to use this in scripts rather than for human consumption.

You could also implement it yourself a little more cleanly:

git for-each-ref --format='%(objectname) %(refname:short)' refs/heads | awk "/^$(git rev-parse HEAD)/ {print \$2}" 

with the benefit of getting the candidate refs on separate lines, with no extra characters.

like image 76
Cascabel Avatar answered Sep 17 '22 03:09

Cascabel