Recently I found myself with a detached HEAD. In Git.
This was the first time I encountered such a thing. When you are working on, or checkout, commits that are not attached to any branch, you have a detached head situation. Your commits are branchless. There is a pretty easy fix to this, and the solution is pretty easy to find on SO.
Check out SO: Why did git detach my head?
I retraced my steps to figure out exactly how this happened.
I created a branch (
git branch newfeature; git checkout newfeature) and then cloned my repository for further work on this branch. This created an ambiguity for git: both the clone and master branch had a branch named
newfeature. When I pulled my work from master with
git pull , the commits were not attached to any branch.
I didn’t recognize this unfamiliar situation. I did notice I couldn’t find all those commits.
- They weren’t visible with
git log newfeature.
git statuswith newfeature checked out showed a clean working directory.
With help from @ddunlop, I was finally able to view the commits with
git log <hash>. I got the commit hash using
git log in my cloned repo.
This is how I resolved the problem.
git checkout <hash>. I checked out my most recent commit using its hash. Git informed me that I was now in a ‘detached HEAD’ state. After that it was easy. I googled the provocative “detached HEAD” message and did some learning.
git checkout newfeature
git branch newfeature_2 6e51426cdb
git merge newfeature_2
git checkout master
git merge newfeature
Then I just deleted the extra branches.
In the process, I also learned about “tracking” branches. Check out the useful SO: Switch branch without detaching head