Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git - Can we recover deleted commits? [duplicate]

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?

like image 443
Atri Avatar asked Jan 12 '16 19:01

Atri


People also ask

Can I recover deleted commits?

The process for recovering a deleted commit is quite simple. All that is necessary is to use `git reflog` to find the SHA value of the commit that you want to go to, and then execute the `git reset --hard <sha value>` command.

Is it possible to recover deleted git branch?

A deleted Git branch can be restored at any time, regardless of when it was deleted. Open your repo on the web and select the Branches view. Search for the exact branch name using the Search all branches box in the upper right. Click the link to Search for exact match in deleted branches.

How do I restore a commit?

The only way to find and recover these unreferenced commits is with git reflog . Using the --hard option, everything is reverted back to the specified commit. This includes the commit history reference pointers, the staging index, and your working directory.

What command's did you use to recover the lost commit?

git revert <sha-1> "Undo" the given commit or commit range. The reset command will "undo" any changes made in the given commit. A new commit with the undo patch will be committed while the original commit will remain in the history as well.


1 Answers

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 
like image 72
Jonathan.Brink Avatar answered Nov 09 '22 22:11

Jonathan.Brink