What is the meaning of the ‘detached HEAD’ state in git?

GitLinuxOpen SourceSoftware & Coding

Explanation − In git HEAD is a reference pointer and points to the current commit in the current branch. The below diagram shows that there are two commits ‘Commit#1’ and ‘Commit#2’, where ‘Commit#2’ is the latest commit. Every commit in Git will have a reference to its previous commit. Here, ‘Commit#2’ will have a reference to ‘Commit#1’. The current branch is master. The master pointer points to the latest commit i.e., ‘Commit#2’. The HEAD points to the master. In other words, the HEAD points to the last commit via the master.

To check where the HEAD is pointing to, we can use the following command in Git bash

$ cat .git/HEAD


ref: refs/heads/master

The output clearly shows that the HEAD refers to the master.

What is Detached HEAD?

In the above example, HEAD points to a branch, which in turn points to a commit. In short, the HEAD points to the commit indirectly. In such a case, the HEAD is said to be attached.

When the HEAD pointer is moved from its default position, we get a warning “detached HEAD state”. This simply means that HEAD is not pointing to any branch, rather it now points to a specific commit. In other words, if the HEAD points to a specific commit, it is said to be detached.

Let us understand this with an example. Execute the following command in the Git bash terminal to view the commit history −

$ git log −−oneline

The output given below indicates that there are 3 commits and the HEAD pointer currently points to master

089ddf4 (HEAD −>master) new line
c81c9ab This is a short description 8a3d6ed first commit

Now let us move the HEAD pointer from its default position and make it point to one of the commit hashes displayed in the output. Here, we will make the HEAD point to the commit hash ‘8a3d6ed’ using the git checkout command.

$ git checkout 8a3d6ed

The output is as shown in the following screenshot.

dell@DESKTOP−N961NR5 MINGw64 /e/tut_repo (master)
$ git checkout 8a3d6ed
Note: switching to '8a3d6ed' .

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can di scard any commits you make in this
state without impacting any branches by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using −c with the switch command. Example:

   git switch −c
Or undo this operation with:
   git switch −

Turn off this advice by setting config variable advice . detachedHead to fal se

HEAD is now at 8a3d6ed first commit
dell@DESKTop−N961NR5 MINGW64 /e/tut_repo ((8a3d6ed.. .))

The warning indicates that the HEAD is detached. This means that HEAD is now pointing to the commit ‘8a3d6ed’. Let us verify this by executing the following command −

$ cat .git/HEAD

The above command will return the contents of the HEAD pointer.


Published on 20-Feb-2021 13:21:28