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
Being in "detached head" means that HEAD refers to a specific unnamed commit (as opposite to a named branch) (cf: https://git-scm.com/docs/git-checkout section Detached head)
To fix the problem, you only need to select the branch that was selected before by
git checkout @{-1}
Here's what I just did after I realized I was on a detached head and had already made some changes.
I committed the changes.
$ git commit -m "..."
[detached HEAD 1fe56ad] ...
I remembered the hash (1fe56ad) of the commit. Then I checked out the branch I should have been on.
$ git checkout master
Switched to branch 'master'
Finally I applied the changes of the commit to the branch.
$ git cherry-pick 1fe56ad
[master 0b05f1e] ...
I think this is a bit easier than creating a temporary branch.
Detached head means you have not checked out your branch properly or you have just checked out a single commit.
If you encounter such an issue then first stash your local changes so that you won't lose your changes.
After that... checkout your desired branch using the command:
Let's say you want branch MyOriginalBranch:
git checkout -b someName origin/MyOriginalBranch
This approach will potentially discard part of the commit history, but it is easier in case the merge of the old master branch and the current status is tricky, or you simply do not mind losing part of the commit history.
To simply keep things as currently are, without merging, turning the current detached HEAD into the master branch:
detached-head
) that will contain the files in their current status:git checkout -b detached-head
git branch -D master
git branch -M master old-master
git branch -M detached-head master
Credit: adapted from this Medium article by Gary Lai.
To further clarify @Philippe Gerber's answer, here it is:
Before cherry-pick
, a git checkout master
is necessary in this case. Furthermore, it is only needed with a commit
in detached head
.
Realizing I had a detached head without knowing how I managed to get it (like three commits away), I also found out that trying to merge
, rebase
or cherry-pick
triggered hundreds of merge-conflicts, so I took a different approach:
(Assuming everything is committed (working tree is "clean"))
Save my commit messages: git log > /tmp/log
Save my working tree: mkdir /tmp/backup && cp -a all_my files_and_directories /tmp/backup
Revert to master
: git checkout master
Remove all the working files and directories: rm ...
Use the backup: cp -a /tmp/backup/. .
git add
and git commit
using messages from saved /tmp/log
, maybe repeating it with different sub-sets of files...
The disadvantage is that you loose your commit history if one file was changed multiple times since master
, but in the end I had a clean master
.