Skip to content

Instantly share code, notes, and snippets.

@npapratovic
Last active December 8, 2022 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npapratovic/849d3ea1314b32272a78feb47b6582f3 to your computer and use it in GitHub Desktop.
Save npapratovic/849d3ea1314b32272a78feb47b6582f3 to your computer and use it in GitHub Desktop.
git Attached / Detached HEAD explained

Detached head means:

  1. You are no longer on a branch,
  2. You have checked out a single commit in the history

If you have no changes: you can switch to master by applying the following command

git checkout master

If you have changes that you want to keep:

In case of a detached HEAD, commits work like normal, except no named branch gets updated. To get master branch updated with your committed changes, make a temporary branch where you are (this way the temporary branch will have all the committed changes you have made in the detached HEAD), then switch to the master branch and merge the temporary branch with the master.

git branch temp

git checkout master

git merge temp

HEAD is a pointer, and it points — directly or indirectly — to a particular commit:

Attached HEAD means that it is attached to some branch (i.e. it points to a branch). Detached HEAD means that it is not attached to any branch, i.e. it points directly to some commit.

In other words:

If it points to a commit directly, the HEAD is detached. If it points to a commit indirectly, (i.e. it points to a branch, which in turn points to a commit), the HEAD is attached.

To better understand situations with attached / detached HEAD, let's show the steps leading to the quadruplet of pictures above.

We begin with the same state of the repository (pictures in all quadrants are the same):

Now we want to perform git checkout — with different targets in the individual pictures (commands on top of them are dimmed to emphasize that we are only going to apply those commands):

This is the situation after performing those commands:

As you can see, the HEAD points to the target of the git checkout command — to a branch (first 3 images of the quadruplet), or (directly) to a commit (the last image of the quadruplet).

The content of the working directory is changed, too, to be in accordance with the appropriate commit (snapshot), i.e. with the commit pointed (directly or indirectly) by the HEAD.

So now we are in the same situation as in the start of this answer:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment