How to fix a Git detached head?


What is a detached head?

Detached head means you are no longer on a branch, you have checked out a single commit in the history. Recently I had to go through this kind of issue while I'm trying to push my code to bitbucket. So I thought of writing a small answer to that question since I found the solution :).

In my case, I wanted to keep the changes. So I'll start with the solution when you want to keep your changes associated with the detached HEAD. Then I'll show how to delete those changes if you don't want to keep them.

Step 01: If you want to keep your changes associated with the detached HEAD

  1. Run git log -n 1; this will display the most recent commit on the detached HEAD. Copy the commit hash.
  2. Run git checkout master
  3. Run git branch New_branch <commit-hash>. This will save your changes in a new branch called New_branch.
See! it's so simple. No need to panic.


Step 02: If you want to delete your changes associated with the detached HEAD


You only need to check out the branch you were on, e.g. git checkout master


Thank you!

Kalpani



Comments