Dealing With “Detached HEAD” State in Git

When you pull in branches from your repository remote or upstream by running say git pull origin master (to pull changes from origin master branch) or git pull upstream non-breaking-space to pull in non-breaking-space branch from upstream; checking out any of these remote branch (e.g. git checkout upstream/non-breaking-space) will result in detached HEAD state because they aren’t proper branches as they do not (currently) exist locally.

In a nutshell, detached HEAD state occurs when you try to checkout something that is not a local branch. It can be a commit, a tag or a remote branch.

when you make changes and commit them, these changes do not belong to any branch but that doesn’t mean the commits are deleted if you eventually switch to another branch.

As displayed in the command line interface, you have to check out a new branch to retain any changes and commits made like so:

Say you created a, staged and committed the change. And then switch to branch SupportElements.

To include the commit we made in detached head state above to our current branch; firstly, the SHA-1 checksum of the commit has to be known.

If you don’t know it, run git reflog show HEAD@{now} -10 to list ten revision history of HEAD.

Note: HEAD is actually a special type of reference that points to another reference. It may point to master or it may not (it will point to whichever branch is currently checked out).

With the SHA-1 checksum of the commit known, run git cherry-pick 1b990a8 to import or rebase the commit on the branch.

I wrote about cherry-pick in a previous post. You might want to check it out.

La Fin!

Don't miss my updates.
Subscribe to Receive Programming, Web development, Git and WordPress Tutorials & all things tech.