Git - Can we recover deleted commits? [duplicate] Ask Question

Git - Can we recover deleted commits? [duplicate] Ask Question

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?

ベストアンサー1

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

おすすめ記事