To reiterate, it means that the HEAD of your project is not pointing to a branch anymore. Instead, it’s pointing to a specific commit. It happens when you run the checkout
command using a commit hash rather than a branch name. As a side-note, you can get hashes of your commits using git log
:
git log
Reasons to detach the HEAD
There are a couple of reasons to check out a specific commit. One of them is to debug or fix issues. In that case, rolling back to a certain moment can be helpful.
Another reason is to experiment with alternative solutions to any given problem. Since the state is simple to correct, that’s a great way to play around with your code.
How to fix
Remember, a detached HEAD is not an error but a feature in Git. With that said, there are two ways to make things go back to “normal.”
Check out a different branch
If you found yourself in this state by accident or finished experimenting, all you need to do is check out another branch. Git will discard your uncommitted code, and your HEAD will point to a branch again.
Create a new branch and commit your code.
If you have some code changes you don’t want to lose, create a new branch and commit your code. Here are the Git commands to do so:
git branch <branch-name>
git checkout <branch-name>
Once you do that, you can commit and push your code to the new branch. As long as you do that before returning to your regular branch, you’ll be fine.
And there you have it! Once you understand the underlying logic in play, the detached HEAD is not so scary and can be quite useful.
If you’d like to get more web development, React and TypeScript tips consider
following me on Twitter,
where I share things as I learn them.
Happy coding!