Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git / detached HEAD, get work back?

Tags:

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?

like image 303
apneadiving Avatar asked Feb 17 '12 00:02

apneadiving


2 Answers

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}.

like image 77
Lily Ballard Avatar answered Sep 21 '22 00:09

Lily Ballard


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.

like image 30
Sven Marnach Avatar answered Sep 20 '22 00:09

Sven Marnach