git,

Recovering from a Git detached HEAD

Oct 13, 2022 · 1 min read · Post a comment

Simply put, a detached HEAD is a Git state that occurs only when you checkout a commit. See Checkout a specific Git commit. In a normal state, HEAD points to a branch name. Under the hood, it points to the latest commit of that branch also known as tip of the branch. Consider a detached state mostly for troubleshooting purposes, like finding a bug as being part of some commit.

Prerequisites

  • Git

Solution

Step 1. Get in a detached HEAD state first.

git checkout <commit-SHA1>

Step 2. If you are in a detached state by a mistake, or you’ve been messing around and do not want to save any changes, just run:

git switch -

or, checkout whatever branch you want to go back to. For instance:

git checkout main

HEAD will point to whatever branch it was pointing to before getting into a detached state.

But, if you do want to save your changes, optionally stage and commit them before creating a new branch.

git switch -c <some_new_branch>

or

git checkout -b <some_new_branch>

Now, it’s up to you if you want to merge this new branch or copy the commit on top of another branch.

Conclusion

To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git