128

I am surprised, I couldn't find the answer to this on SO.

Can we recover/restore deleted commits in git?

For example, this is what I did:

# Remove the last commit from my local branch
$ git reset --hard HEAD~1

# Force push the delete
$ git push --force

Now, is there a way to get back the commit which was deleted? Does git record(log) the delete internally?

Atri
  • 5,511
  • 5
  • 30
  • 40
  • 1
    You can find your previous HEAD commit through git reflog and check it out again – Martin G Jan 12 '16 at 19:08
  • Just in case someone wonders: the method presented here will work IF you have ever had that commit IN your local machine (either you commit in the local repository or fetch the change). If you want to restore a commit someone else has pushed & deleted on GitHub / GitLab server, take a look at the API of GitHub, there will be API to help create a branch from the old commit. – Hoàng Long Dec 29 '20 at 11:30

3 Answers3

353

To get back to that commit you can use the reflog to look up it's ref.

Reference logs, or "reflogs", record when the tips of branches and other references were updated in the local repository.

Run this command:

git reflog

Scan the first few entries, and find the commit that was lost. Keep track of the identifier to that commit (you can use either the 1st or 2nd columns). Let's call the identifier "ID".

If you have not made any extra work since you did the reset --hard you can do:

git reset --hard ID
git push -f origin master

If you have made other work since the reset, you could cherry-pick if back onto your branch like this:

git cherry-pick ID
git push origin master
Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115
  • 1
    Isn't reflog something which is stored locally and differs from client to client? - In theory could you have missed the most recent commits, if your local branch was never put up-to-date prior to the destruction. Is that correct? – bvdb Oct 04 '22 at 14:54
  • Yes, reflog is stored locally and will be unique to you – Jonathan.Brink Oct 04 '22 at 18:20
54

Yes, You can find your commit in reflog use:

git reflog

to display all commits which are/were created in your repository - after this you should checkout to removed commit by checkout command

git checkout <your commit-SHA>

or cherry-pick it by:

git cherry-pick <your commit-SHA>
Konrad Krakowiak
  • 12,285
  • 11
  • 58
  • 45
9

Try git reflog, aka Reference logs, it allows you to go back to history in your local repo.

https://git-scm.com/docs/git-reflog

Chaoyu
  • 842
  • 8
  • 16