DEV Community

Cover image for Git Head and Detached Head
Ashutosh Sharma
Ashutosh Sharma

Posted on

Git Head and Detached Head

Git Head and Detached Head

HEAD normally refers to a named branch.

 **$git checkout master**
 Already on 'master'
 Your branch is up to date with 'origin/master’.
*** $ cat .git/HEAD***
 ref: refs/heads/master
Enter fullscreen mode Exit fullscreen mode

If we switch the branch, HEAD will also change the reference to a new branch.

 **$git checkout -b feature_branch**
 Switched to a new branch ‘feature_branch’
 **$ cat .git/HEAD**
 ref: refs/heads/feature_branch
Enter fullscreen mode Exit fullscreen mode

It is also possible to check out a specific commit in Git using the SHA1 hash of the commit.

**$ git checkout e81c5ca4f2a1093c6c8e1e34a3f185f3db07f377**

Note: switching to 'e81c5ca4f2a1093c6c8e1e34a3f185f3db07f377'.

You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard 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 <new-branch-name>
Or undo this operation with:
git switch -
Turn off this advice by setting config variable advice.detachedHead to false
HEAD is now at e81c5ca first commit
Enter fullscreen mode Exit fullscreen mode

Let’s check what is HEAD now referring to:

**$ cat .git/HEAD
 e81c5ca4f2a1093c6c8e1e34a3f185f3db07f377**
Enter fullscreen mode Exit fullscreen mode

This is the situation when the HEAD is referring to a Commit instead of a branch is called Detached HEAD.

Top comments (0)