12

I lost my last commit because I accidentally ran "git reset --hard HEAD^". Note: I didn't want to put the "^" at the end.

Is there any way to get it back? It was 2 days of work :(

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
Scott Hernandez
  • 7,452
  • 2
  • 34
  • 25
  • 2
    In any case, do NOT use git gc. That will remove the unlinked commits permanently. – Tronic Feb 27 '10 at 17:41
  • No, gc will *not* lose that commit unless you've gone out of your way to make it easier for git to forget your commits (disabling or aggressively pruning). Anyone who's spent enough time to learn how to configure git to lose their most recent commit would at least know to not ask the question. – Dustin Feb 27 '10 at 19:27
  • 5
    `git gc` by default do not remove unlinked commits if they are in reflog up to 30 days in the case of unreferenced commits (by default). – Jakub Narębski Feb 28 '10 at 14:56

3 Answers3

26

I think that this article is what you are looking for. According to the article, your commit is "gone," but not garbage collected - sort of like the recycle bin in Windows.

You run git fsck --lost-found to find the 'dangling commit', and look at it with git reflog, then merge the dangling commit with your current branch, git merge 7c61179.

Benjamin Manns
  • 9,028
  • 4
  • 37
  • 48
  • Thanks. That did it. I knew it was just floating around in there someplace, unlinked from the branch. – Scott Hernandez Feb 27 '10 at 17:45
  • In combination with difftool, I've solved my "lost commit" problem: git fsck --lost-found (dangling commit hashes are displayed) git difftool SOME_HASH somefolder/ (I've tried all dangling commits, until I've found the needed one) – Vladimir Djuricic May 22 '13 at 13:47
22

git makes it really easy to go back to a prior state and works very hard to prevent you from losing any data you've committed. It's this reason you should commit often. I've got a command git trash that does that git reset --hard state, but after writing a commit so that I can undo the hard reset if I need.

For the most recent state (i.e. your exact case), just do git reset --hard ORIG_HEAD to undo what you just did.

You can do a time-based reset: git reset --hard '@{5 minutes ago}' to put yourself in a prior state based on time (there are lots of options you can use, for example, git reset --hard '@{yesterday}' to pretend today never happened).

Otherwise, browse the git reflog output to find the thing before the action you feel put you in a bad state and reset to that.

Dustin
  • 89,080
  • 21
  • 111
  • 133
7

If you know the commit ID (e.g. scroll back on your terminal or use git reflog),

git reset --hard 61567de5d9

Where 61567de5d9 are the first digits of the latest (lost) commit.

Tronic
  • 10,250
  • 2
  • 41
  • 53