How to fix a Git detached head

How to solve detached head issue

HEAD is the symbolic name for the currently checked out commit. When HEAD is not detached (the “normal”1 situation: you have a branch checked out), HEAD actually points to a branch’s “ref” and the branch points to the commit. HEAD is thus “attached” to a branch. When you make a new commit, the branch that HEAD points to is updated to point to the new commit. HEAD follows automatically since it just points to the branch.

The branch named “master” is checked out.

When HEAD is detached, it points directly to a commit – instead of indirectly pointing to one through a branch. You can think of a detached HEAD as being on an unnamed branch.

Solution on Git detached could issue

To fix detached head, you should create a branch that points to the commit currently pointed to by your detached HEAD:

This will reattach your HEAD to the new temp  branch.

If your new temp branch looks good, you may want to update (e.g.) master  to point to it:

You can then delete the temporary branch:

Finally, you will probably want to push the reestablished history:

You may need to add --force  to the end of this command to push if the remote branch can not be “fast-forwarded” to the new commit (i.e. you dropped, or rewrote some existing commit, or otherwise rewrote some bit of history).

If you were in the middle of a rebase operation you should probably clean it up. You can check whether a rebase was in process by looking for the directory .git/rebase-merge/ . You can manually clean up the in-progress rebase by just deleting that directory (e.g. if you no longer remember the purpose and context of the active rebase operation). Usually you would use git rebase --abort , but that does some extra resetting that you probably want to avoid (it moves HEAD back to the original branch and resets it back to the original commit, which will undo some of the work we did above).