Git - Can we recover deleted commits?

I am surprised I could not find an 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 return a command that has been deleted? Does git write (delete) log inside?

+7
git git-commit restore
source share
3 answers

To return to this post, you can use reflog to find it.

Help logs or "logs", a record of when branch ends and other links have been updated in the local repository.

Run this command:

 git reflog 

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

If you haven't done any extra work since you did a reset -hard, you can do:

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

If you did another job since reset, you could choose cherry-pick if you go back to your branch, like this:

 git cherry-pick ID git push origin master 
+32
source share

Yes, you can find your commit in reflog :

 git reflog 

to display all the commits that were / were created in your repository - after that you should check to remove commit with the checkout command

 git checkout <your commit-SHA> 

or cherry pick:

 git cherry-pick <your commit-SHA> 
+4
source share

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

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

+1
source share

All Articles