Git / detached HEAD, get work back?

2019-03-18 00:00发布

问题:

I made a dozens of commits on what I thought was my branch, then checked out another branch.

Willing to go back to my initial branch, I didn't find my updated code. After looking at my history in console, I understood I worked in a detached branch...

Is it somehow possible to get the job I've done on the detached branch?

回答1:

Yes. You can use the reflog. Try git log -g HEAD. This will show you the reflog for HEAD, i.e. every single commit that HEAD has pointed to, and the reason why it changed to that commit. You should be able to find your command that checked out the branch, and see what the previous commit was.

You can also use other syntax to index into the reflog. If you just performed the git checkout branch, then HEAD@{1} will refer to the previous checked-out commit (so you can git checkout HEAD@{1} to get back to it). Or if you know that 10 minutes ago HEAD was pointing to the right thing, you can use git checkout HEAD@{10.minutes.ago}.



回答2:

Relax, everything is still there :)

Just call

git reflog

and git will tell you to what commits HEAD pointed before. There will be a line like

checkout: moving from c70e36e25ac2dbedde6cb376719381fe0ab53f19 to master

telling you the SHA1 of the tip of your commits with a detached head. Create a new branch pointing to that tip using

git branch saved-commits c70e36e25ac2dbedde6cb376719381fe0ab53f19

Now you can rebase that branch on top of the branch the commits were supposed to go to.