Mastering git, Part 13, Detached HEAD in Git

Detached HEAD

Before everything, let’s have a look at some stuff. Everything in Git is about commits, and many git commands accept commits as a parameter, i.e.

We have to understand how to reference commits.

Hash

The SHA-1 hash of a commit is the most straightforward method to refer to it. In the

output, you may get the hash of each of your commits.

You just need to provide the minimum number of characters necessary to uniquely identify the commit when giving it to other Git commands. For instance, you may use the

command to examine the aforementioned commit.

Resolving a branch, tag, or other indirect references into the relevant commit hash can be done by using the

command.

Refs

A ref is an indirect way (a user-friendly alias) of referring to a commit. Refs are stored as plain text files in the

directory of your git.

 

HEAD

HEAD is the symbolic name for the currently checked-out commit. If you open the HEAD file you will see it is pointing to a branch, for instance:

If you open the

directory, you will see a file for each one of your branches:

Creating a new branch is simply a matter of writing a commit hash to a new file, and that’s the reason why Git branches are so lightweight.

The tags and remotes directory works the exact same way. So now let’s see what is a detached HEAD.

If HEAD file, instead of pointing to a branch, points directly to a commit, your HEAD is detached when your head is pointing into a commit and not into a branch.

Complete Example

Now if you run

it will show you where HEAD is pointing:

Now if you run git log and find the HASH of the commit B and checkout that commit:

You are in a ‘detached HEAD’ state. If you run:

It will indicate a commit and not a branch, actually the HASH-ID of the commit-B

How to solve the detached HEAD

You can simply create a temp branch from where you are, switch to master, merge your temp into your master and delete the temp branch.

 

Refs: [1]

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x