How to fix a Git detached head with example


A “detached HEAD” state in Git means that you are not currently on a branch, but rather you are at a specific commit, which is not associated with a branch name. This can happen if you checkout a specific commit or tag, or if you make changes to a branch but don’t create a new commit.

To fix a detached HEAD state in Git, you can either create a new branch or revert back to an existing branch. Here’s how to do it with an example:

  • First, run the git branch command to see which branch you are currently on. If you are in a detached HEAD state, you will see an asterisk next to the commit hash.
$ git branch
* (HEAD detached at <commit-hash>)
  master
  • Create a new branch at the current commit by running the git branch command followed by the name of the new branch. For example, to create a new branch called “new-branch”:
$ git branch new-branch
  • Switch to the new branch using the git checkout command:
$ git checkout new-branch
  • Alternatively, if you want to go back to an existing branch, you can use the git checkout command followed by the name of the branch:
$ git checkout master
  • Finally, you can delete the branch that was created when you were in a detached HEAD state using the git branch -d command:
$ git branch -d

In this example, you can delete the branch “new-branch” by running:

$ git branch -d new-branch

By creating a new branch or switching back to an existing branch, you will no longer be in a detached HEAD state and your changes will be associated with a branch name.