I have a really simple Git project, with just a Master branch and no origins.
Somewhere along the line I accidentally created a detached HEAD in my project, and then after making a bunch of commits on that detached HEAD
, tried to merge it back into my Master
branch. I was doing this in SourceTree, and at first the merge seemed to work (the graph showed master going into head, and there were merge conflicts which I fixed), but then I double clicked on Master
to switch to that branch and then suddenly my HEAD
disappeared. I can't find it anywhere in SourceTree under All Branches, and git branch
and git log
on the command line only show my Master branch too.
Is there anyway to get back my commits from my lost detached HEAD
?
To hard reset files to HEAD on Git, use the “git reset” command with the “–hard” option and specify the HEAD. The purpose of the “git reset” command is to move the current HEAD to the commit specified (in this case, the HEAD itself, one commit before HEAD and so on).
If you want to keep changes made with a detached HEAD, just create a new branch and switch to it. You can create it right after arriving at a detached HEAD or after creating one or more commits. The result is the same. The only restriction is that you should do it before returning to your normal branch.
Here is what worked for me:
git reflog
command to find out the head version that disappeared. git checkout @{-1}
to move HEAD back to the one disappeared. The number -X
is how many commits the disappeared from current head. -1
means the disappeared version is 1
commit away from current HEAD. I can't find it anywhere in SourceTree
Go back to the command-line interface and do a git reflog.
You should be able to find back the SHA1 of your HEAD in that log.
Note that you wouldn't have needed to "merge" your detached HEAD branch back to master.
You simply could have reset master to your current detached HEAD commit.
See "How to fix a Git detached head?"
git checkout master
In pure SourceTree fashion (as in this thread)
You could also have checked out an existing branch, then used right-click on the latest commit and selected
Reset <branch>
to this commit to move the branch pointer to where you want it to be.When
HEAD
is displayed, it means that you're on a detached HEAD, which means you have no branch checked out and any commits won't move any branches when they're made. If you checkout a detached HEAD in SourceTree, it will warn you fairly obviously, so maybe this was done on the command line beforehand and you saw the after effects in SourceTree.
Alternative:
create a branch from my "
HEAD
" branch (which isn't really a branch at all) using the new branch command. At that point head is gone.
Then I was able to merge that branch with master and delete the unwanted branch I had created fromHEAD
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With