How to fix Detached HEAD state in git?
Sometimes we end of checking out the old versions without creating a new branch. In this situation HEAD becomes detached because it point no where. Once we are in this situation, there are multiple outcomes possible:
- Discard the changes and return to master
- Merge changes between master and detached head.
- Retain the changes by forcing
master
branch to attach to detached head.
This blog post covers the third scenario. If you want to retain the changes and reset master branch, then only follow these steps:
- Create a temporary branch to
git branch temp
- Checkout the current branch by typing
git checkout temp
- Forcefully rename the master branch to temp
git -f master temp
- Checkout the master branch by typing
git checkout master
- Optional: Remove the temp branch by using
git branch --delete temp