The hydra-universe twisting its body scaled in stars.

How to undo a git reset hard and branch delete

Git 找回reset --hard的代码及删除的分支

People make mistakes all the time.

I remember the first time I used git reset --hard + git push -f was in early 2013. I thought it was just a small commit, but I ended up pushing a bunch of useless code to github. What should I do? At this time, some seniors came out and told me that even if the code is pushed to the server, it can still be modified, and told other colleagues not to push the code for the time being, and finally solved the problem with reset-hard and force.

Finally, after all these years, I seem to have become a "senior" (but the level has not improved too much).

Today a colleague suddenly said the code was lost - after reset hard, force push to github, in a panicked looking ...... all the memory just came back, in the previous accident, I was also apprehensive,.

Back to the beginning of this article, people will always make mistakes. In the process of correcting mistakes, we may will also make mistakes. Although the probability of two mistakes is not that big, it still may happen. So is it possible to retrieve code after reset --hard? The answer is yes! Git never deletes a commit. This is where reflog comes into play.

The official description of reflog is this:

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

We can get 2 pieces of information from it:

  1. It is a change log for refs, so operations like git reset or git cherry-pick are logged;

  2. It only exists locally, so you can think of it as the local undo history.

Basic Reflog operations

List reflogs:

git reflog


git log --walk-reflogs

You can see that all your previous changes are still there, so you should feel comfortable - even if you did reset --hard, you won't lose them. At this point you should be familiar with the routine after that, find the commit you need and reset it.

Restore a branch

Similarly, a branch deleted with -D can be recovered. Use reflog to check the record, find the hash of the commit before the branch was deleted, for example, 4c84318, and then do this:

git branch <branch-name> 4c84318
< Back