26

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
NoBugs
  • 9,310
  • 13
  • 80
  • 146
  • dup of http://stackoverflow.com/questions/4845505/gitx-how-do-i-get-my-detached-head-commits-back-into-master? – smparkes Jan 27 '12 at 22:56
  • Does this answer your question? [How can I reconcile detached HEAD with master/origin?](https://stackoverflow.com/questions/5772192/how-can-i-reconcile-detached-head-with-master-origin) – mkrieger1 Jul 14 '22 at 18:52

2 Answers2

41

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.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
23

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.

Ian Gow
  • 3,098
  • 1
  • 25
  • 31