You are in detached HEAD state and how to fix in git
Have you ever got this message in git saying “You are in detached HEAD state”…
the HEAD is a git pointer to a branch that tells you which branch you are on. Somehow this pointer got lost. This tutorial will tell you how to recover from detached HEAD state, because this is not a good state to be in for long. But don’t panic, it is okay for now. We can recover from it.
The proper way to recover from it depends on the situation and how it got into that state in the first place. Let’s go through a sample situation ..
1. We start off with a clean repository. Doing “git status” shows ..
git status
# On branch master
nothing to commit, working directory clean
This is a good state, this is what we like to see.
2. We make a change to a file in our repository (without branching, which is what we should have done). git status shows one modified file with changes not staged for commit.
3. Now we want to abandon our changes and fetch back the original file from the checked in version of your local repository. What you should do is …
git checkout — <filename>
But instead, let’s say you made an error and did a checkout from origin …
git checkout origin
And it gave you the “detached HEAD” state error.
4. To recover, create a branch named “temp” and switch to it…
git branch temp
git checkout temp
By switching to temp, you are attaching HEAD to the temp branch.
Git status now will show “On branch temp”. This is good.
5. You want to be back on master, so switch to master …
git checkout master
6. And then delete the temp branch (see tutorial)…
git branch -d temp
7. Now you are back to HEAD on master. If you still want to adandon current file change, pull from repository with the command …
git checkout — <filename>