HEAD detached from origin/master

head detached

If Git gives the following message:

HEAD detached from origin/master

it means that the commits you are making do not belong to a branch.

To understand this message better, it helps to understand a few concepts from Git. The concepts are:

Let me explain by taking an empty git project as our example.

Assume we have created a Git repository and don’t create a branch. We work with the default branch origin/master which is now our current branch.

The first time you have a finished unit of work, you create a commit that is added to the commit tree.

Commit 1:

SHA1 1a-2b-3c-4d-5e-6f
Parent null
Message Make it so!

Notice how the Parent is null. The first commit never has a parent. The commit tree now has 1 commit and the HEAD pointer can be pointed to it by referencing its SHA1.

Head looks like this:

HEAD 1a-2b-3c-4d-5e-6f

In other words, the HEAD Pointer points to the tip of the current branch. If you commit new changes, a commit will be created with parent set to 1a-2b-3c-4d-5e-6f

Let’s create a second commit

Commit 2:

SHA1 7g-8h-9i-1z-2y-3x
Parent 1a-2b-3c-4d-5e-6f
Message Cleanup stuff

Head now looks like this:

HEAD 7g-8h-9i-1z-2y-3x

A table of commits would look like this:

7g-8h-9i-1z-2y-3x <=– HEAD

If for some reason HEAD points to a commit that does not belong to a branch, we are dealing with a detached HEAD.

Fix detached HEAD

git checkout origin/master

If you made commits while HEAD was detached, Git will warn you:

Warning: you are leaving 3 commits behind, not connected to
any of your branches:

  b1be274 v1.0
  d438323 css
  539a8f7 cleanup

If you want to keep them by creating a new branch, this may be a good time
to do so with:

 git branch <new-branch-name> b1be274
git branch fix-detached-HEAD b1be274
git checkout -B master fix-detached-HEAD

You are now back on the master branch and Git will show:

Your branch is ahead of 'origin/master' by 3 commits.
  (use "git push" to publish your local commits)

To update the server, execute:

git push origin master

Tips on working with Git

Fixing the repository with the command line might lead to mistakes that delete code. It can never hurt to create a backup of your code before trying to execute all these commands. Better safe than sorry!