18

Working on local master branch:

git commit -m "Lots of important commits"
git reset --hard origin/master

How can I retrieve the commits that have been lost as a result of the git reset (from the remote)?

EDIT: note this is not about retrieving uncommitted changes.

4
  • You cannot pull that code from the remote repository, you only committed it to your local one, then reset it to the remote one. The code was never pushed to the remote. I try to always create a branch like "temp" before a hard reset, just so I have something referencing those commits in case I realize I need them.
    – Turch
    Commented Nov 13, 2014 at 17:35
  • 1
    You're pretty much screwed
    – sjagr
    Commented Nov 13, 2014 at 17:36
  • 2
    not a duplicate of that one, since this example is trying to recover commits, not uncommitted changes. Commented Nov 13, 2014 at 17:45
  • @Turch sorry that was leading, I meant how can the commits be retrieved as a result of my erroneous pull from the remote repository
    – chrisjleu
    Commented Nov 13, 2014 at 19:41

1 Answer 1

52

If you committed it, nothing is lost.

If you have the reference of the commit, you can just git reset --hard <sha> to that precise commit.

In case you don't you can always use git reflog to retrieve the sha before performing the hard reset.

For instance if git reset --hard origin/master is the last command you run, you can do

git reset HEAD@{1}
1
  • Strangely, this half worked, in that it brought back a file I had committed and lost, but didn't bring back the directory that contained the file (so I had to recreate the directory manually).
    – stevec
    Commented Feb 5, 2019 at 18:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.