NoBugs
NoBugs

Reputation: 9512

How to recover commit from 'detached head state'?

I checked out another branch with updates then made a few changes, switched back to the main git and now the changes disappeared! Can I get them back? the terminal was basically:

$ git commit
[detached HEAD 7c09e17] Fixed some stuff
  files changed, insertions(+), deletions(-)
$ git push master
fatal: 'master' does not appear to be a git repository
fatal: The remote end hung up unexpectedly
$ git checkout master
Previous HEAD position was 7c09e17... Fixed some stuff
Switched to branch 'master'
$ git merge theother/directory

Upvotes: 26

Views: 13015

Answers (2)

Ian Gow
Ian Gow

Reputation: 3535

I had a similar problem. I found git reflog to be a life-saver. In case it helps illustrate it use, here's the output:

e3191c5 HEAD@{0}: checkout: moving from ec31ccf0735240d0cdc5a44fd443039c3caa43f0 to master
ec31ccf HEAD@{1}: commit: Added code and data for simulation.
781b9ee HEAD@{2}: checkout: moving from 3bd804e635b913840c71b7f8a33665460580d45f to 781b
3bd804e HEAD@{3}: checkout: moving from master to 3bd804

My situation was a bit different in that I had made a commit while in a detached HEAD state starting from a very old commit.

If I simply wanted to merge ec31ccf0735240d0cdc5a44fd443039c3caa43f0 (aka ec31ccf, which is where I had been) into master, I think git merge ec31ccf or git rebase ec31ccf might have worked. But this would be mostly merging ancient history in my case (with merge conflicts, etc.).

Instead, I just wanted to recover what I'd done on ec31ccf, and git cherry-pick ec31ccf worked nicely.

Upvotes: 24

Matthew Flaschen
Matthew Flaschen

Reputation: 285057

Assuming you're still on master:

git merge 7c09e17

should be enough. git is usually good about telling you the commit IDs, if you watch the terminal.

Upvotes: 41

Related Questions