W3docs

How to Reconcile Detached HEAD with Master/Origin in Git

The tutorial covers about how to reconcile the detached HEAD with master/origin. Get to know what is HEAD and give a solution to your problem immediately.

Before showing how to reconcile detached <kbd class="highlighted">HEAD</kbd> with master/origin, let’s figure out what is <kbd class="highlighted">HEAD</kbd>. The <kbd class="highlighted">HEAD</kbd> 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 reconcile the detached HEAD with master/origin

Let’s create a branch pointing to the commit currently pointed to by detached <kbd class="highlighted">HEAD</kbd>.

Creating a branch

Run the following to reattach your <kbd class="highlighted">HEAD</kbd> to the new temp git branch:

git create new branch and reattach head

git branch temp
git checkout temp

or abbreviate the above commands as:

git create new branch and reattach head

git checkout -b temp

Comparing

Compare the current commit and its history with the target branch you are going to work on (assuming the remote is origin, which is the default):

git compare the current commit and its history

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 update master

git branch -f master temp
git checkout master

or

git update master

git checkout -B master temp

Warning: git branch -f master will overwrite the master branch, discarding any unpushed commits on it.

Deleting the branch

Delete the branch by executing the following:

git delete branch

git branch -d temp

Pushing

Push the re-established history with the git push command:

git push

git push origin master

If the remote branch cannot be fast-forwarded to the new commit, attach the --force-with-lease option to <kbd class="highlighted">git push</kbd>:

git push with force

git push --force-with-lease

Detached HEAD

The Detached <kbd class="highlighted">HEAD</kbd> 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 git checkout command updates <kbd class="highlighted">HEAD</kbd> to point to the specified branch or commit. There’s no problem when <kbd class="highlighted">HEAD</kbd> points to a branch, but when it points directly to a commit, it enters a detached HEAD state. When attached, <kbd class="highlighted">HEAD</kbd> points to a branch reference, which in turn points to a commit. When you create a new commit, the branch that <kbd class="highlighted">HEAD</kbd> points to is updated to point to that newly created commit. <kbd class="highlighted">HEAD</kbd> will follow automatically because it just points to the branch.