Fix a Git detached head?
I was doing some work in my repository and noticed a file has 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?
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, ie HEAD^).
If you want to delete your changes associated with the detached HEAD
You only need to checkout the branch you were on, eg
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
git log -n 1
; this will display the most recent commit on the detached HEAD. Copy-and-paste the commit hash. git checkout master
git branch tmp <commit-hash>
. This will save your changes in a new branch called tmp
. master
, run git merge tmp
from the master
branch. You should be on the master
branch after running git checkout master
. If you have changed files you don't want to lose, you can push them. I have committed them in the detached mode and after that you can move to a temporary branch to integrate later in master.
git commit -m "....."
git branch my-temporary-work
git checkout master
git merge my-temporary-work
Extracted from:
What to do with commit made in a detached head
How to exit (“fix”) detached HEAD state when you already changed something in this mode and, optionally, want to save your changes.
This solution works without creating a temporary branch.
Commit changes you want to keep. If you want to take over any of the changes you made in detached HEAD state, commit them. Like:
git commit -a -m "your commit message"
Discard changes you do not want to keep. The hard reset will discard any uncommitted changes that you made in detached HEAD state:
git reset --hard
(Without this, step 3 would fail, complaining about modified uncommitted files in the detached HEAD.)
Check out your branch. Exit detached HEAD state by checking out the branch you worked on before, for example:
git checkout master
Take over your commits. You can now take over the commits you made in detached HEAD state by cherry-picking, as shown in my answer to another question.
git reflog
git cherry-pick <hash1> <hash2> <hash3> …
上一篇: 如何在git重置后重新获得东西
下一篇: 修复Git分离的头部?