Skip to content
Fix Code Error

How do I fix a Git detached head?

March 13, 2021 by Code Error
Posted By: Anonymous

I was doing some work in my repository and noticed a file had local changes. I didn’t want them anymore so I deleted the file, thinking I can just checkout a fresh copy. I wanted to do the Git equivalent of

svn up .

Using git pull didn’t seem to work. Some random searching led me to a site where someone recommended doing

git checkout HEAD^ src/

(src is the directory containing the deleted file).

Now I find out I have a detached head. I have no idea what that is. How can I undo?

Solution

Detached head means you are no longer on a branch, you have checked out a single commit in the history (in this case the commit previous to HEAD, i.e. HEAD^).

If you want to delete your changes associated with the detached HEAD

You only need to checkout the branch you were on, e.g.

git checkout master

Next time you have changed a file and want to restore it to the state it is in the index, don’t delete the file first, just do

git checkout -- path/to/foo

This will restore the file foo to the state it is in the index.

If you want to keep your changes associated with the detached HEAD

  1. Run git branch tmp – this will save your changes in a new branch called tmp.
  2. Run git checkout master
  3. If you would like to incorporate the changes you made into master, run git merge tmp from the master branch. You should be on the master branch after running git checkout master.
Answered By: Anonymous

Related Articles

  • What's the difference between "git reset" and "git…
  • How do I ignore files in Subversion?
  • Checkout another branch when there are uncommitted changes…
  • How to resolve "local edit, incoming delete upon update"…
  • SVN Error - Not a working copy
  • Various ways to remove local Git changes
  • Why did my Git repo enter a detached HEAD state?
  • How to git-svn clone the last n revisions from a Subversion…
  • Git: Create a branch from unstaged/uncommitted changes on…
  • Git Using Remote Branch

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Add a new item to a dictionary in Python

Next Post:

How to convert strings into integers in Python?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error