3

I made a commit while on the (no branch) branch then did a pull, realized I was on the wrong branch and did a 'checkout master' and another pull. I now can't find my original commit to push on the master branch and I can't switch to the (no branch). Is there a way to resurrect my commit or get the diff?

Patrick Auld
  • 1,407
  • 3
  • 15
  • 25
  • 2
    Maybe - does `git reflog` show the commit - you could the maybe pull it into a real branch? – Adrian Cornish Sep 05 '12 at 04:00
  • 1
    @AdrianCornish this is likely to be the correct answer: please post it below for votes. – Alex Brown Sep 05 '12 at 04:19
  • Does this answer your question? [How can I recover a lost commit in Git?](https://stackoverflow.com/questions/10099258/how-can-i-recover-a-lost-commit-in-git) – starball May 29 '23 at 22:20

1 Answers1

6

The git reflog will list for you all the commits you did, and a (for instance) git merge HEAD@{1} will merge it back into your branch.

$ git reflog
734713b... HEAD@{0}: commit: fixed refs handling, added gc auto, updated
d921970... HEAD@{1}: merge phedders/rdocs: Merge made by recursive.
1c002dd... HEAD@{2}: commit: added some blame and merge stuff

From git rev-parse:

<refname>@{<n>}, e.g. master@{1}

A ref followed by the suffix @ with an ordinal specification enclosed in a brace pair (e.g. {1}, {15}) specifies the n-th prior value of that ref.

Note that a git rebase -i would do the same.

The Revision Selection page mentions:

It’s important to note that the reflog information is strictly local — it’s a log of what you’ve done in your repository.
The references won’t be the same on someone else’s copy of the repository; and right after you initially clone a repository, you'll have an empty reflog, as no activity has occurred yet in your repository.

The config gc.reflogExpire specifies when to removes reflog entries older than this time; defaults to 90 days.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
Adrian Cornish
  • 23,227
  • 13
  • 61
  • 77
  • This is often true, although can fail depending upon git reflog configuration. – Alex Brown Sep 05 '12 at 04:22
  • Why do I remember reading something about the last 20 commits only - or am I wrong – Adrian Cornish Sep 05 '12 at 04:29
  • Thanks for the fast answer! I came in this morning and after fixing some whitespace conflicts get everything merged in. – Patrick Auld Sep 05 '12 at 16:55
  • @VonC Thank you - really this is your answer - mine was really just a comment on what I roughly thought might work - you answer actually explains it and the credit belongs to you. – Adrian Cornish Sep 06 '12 at 04:00
  • You JUST saved my life with this command! GIT is awesome! (Awesomely complicated but ultimately saved the day!) - Thanks! – Norman H Feb 11 '15 at 18:41