How to Reconcile Detached HEAD with Master/Origin in Git
Before showing how to reconcile detached HEAD with master/origin, let’s figure out what is HEAD. The HEAD is a symbolic reference to the branch you are currently on. It contains a pointer to another reference. It is the last checked out point in a repository.
Steps to reconciling the detached HEAD with master/origin
Let’s create a branch pointing to the commit currently pointed to by detached HEAD.
Creating a branch
Run the following to reattach your HEAD to the new temp git branch:
git branch temp
git checkout temp
or abbreviat the above commands as:
git checkout -b temp
Comparing
Compare the current commit and its history with the normal branch you are going to work on (suppose, the name of remote is origin, which is by default):
git log --graph --decorate --pretty=oneline --abbrev-commit master origin/master temp
git diff master temp
git diff origin/master temp
Updating master
Update master to point to it like this:
git branch -f master temp
git checkout master
or
git checkout -B master temp
Deleting the branch
Delete the branch by executing the following:
git branch -d temp
Pushing
Push the re-established history with the git push command:
git push origin master
If the remote branch can not be fast-forwarded to the new commit, attach the --force option to git push:
Update master to point to it like this:
git branch -f master temp
git checkout master
or
git checkout -B master temp
Delete the branch by executing the following:
git branch -d temp
Push the reestablished history with the git push command:
git push origin master
If the remote branch can not be fast-forwarded to the new commit, attach the --force option to git push:
git push --force
Detached HEADS
The Detached HEAD state warns that your activity is “detached” from the project’s development. It allows checking out commits and examining the repository’s older state without creating a local branch. The HEAD updates the git checkout command to point the specified branch or commit. There’s no problem when HEAD points to a branch, but when it points to a commit, it moves to a detached HEAD state. When HEAD is not detached, it points to a branch’s reference, and the branch points to the commit. Thus, HEAD is attached to a branch. When you create a new commit, the branch that HEAD points to is updated so as to point to that newly created commit. HEAD will follow automatically because it just points to the branch.