How to fix a Git detached head

Navigating through Git can sometimes lead developers to a peculiar state known as a "detached HEAD." While the term might sound alarming, it's a common situation in Git. In this Answer, we'll discover the concept of a detached HEAD and walk you through the steps to fix it.

What is a detached HEAD?

In Git, the term "HEAD" refers to a pointer that indicates the current commit you're on. Typically, HEAD points to the latest commit in the branch you're working on. However, when you check out a specific commit that isn't the latest one, Git warns you that you're in a "detached HEAD" state.

This means you're no longer working on a branch; instead, you're working directly on a commit. Any changes made in this state won't belong to any branch, making them harder to keep track of.

How did I end up here?

A common scenario leading to a detached HEAD is when you check out a commit by its hash:

git checkout 4e2c8a2

Git will notify you with a message like:

Note: checking out '4e2c8a2'.
You are in 'detached HEAD' state...

Fixing a detached HEAD

Step 1: Before making any changes, check the commits you've made in the detached state:

git log --oneline

This will show you a list of commits, helping you identify any changes you made while detached.

Step 2: If you wish to keep the changes made in the detached state, create a new branch:

git checkout -b new-branch-name

This will save your changes to a new branch, ensuring they're not lost.

Step 3: If you don't want to keep the changes, switch back to a known branch:

git checkout master

Replace master with the name of your desired branch. This will bring HEAD back to the tip of that branch, resolving the detached state.

Practical example

Imagine you're exploring old commits and accidentally end up in a detached HEAD state:

git checkout 9f7d2cb

Git warns you about the detached HEAD. To fix this:

  1. Check the commits:

git log --oneline

Suppose you see a commit with the message "Fix typo." You decide to keep this change.

  1. Create a new branch:

git checkout -b typo-fix

Now, your changes from the detached state are safely stored in the typo-fix branch.

Conclusion

A detached HEAD in Git might sound intimidating, but with a clear understanding and the right commands, it's a breeze to handle. Whether preserving changes or reverting to a previous state, Git offers the flexibility to navigate and rectify any situation. So, the next time you find yourself with a detached HEAD, remember this Answer and confidently steer your way back to stable ground.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved