Recover the misoperation of git reset -hard

Reprinted from: http://www.cnblogs.com/mliudong/archive/2013/04/08/3007303.html

Working with Git can sometimes be done with care, especially when it comes to advanced operations such as reset, rebase and merge. Even for small operations like deleting a branch, I'm worried about data loss.

Not long ago, before I did something big (rebasing), I always backed up my entire repository, just in case. Only recently I found out that git's history is immutable, which means you can't change anything that has already happened. Any operation you do is just a modification of the original operation. That is, even if you delete a branch, modify a commit, or force a reset, you can still roll back those operations.

Let's look at some examples:

$ git init
$ touch foo.txt
$ git add foo.txt
$ git commit -m "initial commit"

$ echo 'new data' >> foo.txt
$ git commit -a -m "more stuff added to foo"

You now look at the git history and you can see two commits:
$ git log
* 98abc5a (HEAD, master) more stuff added to foo
* b7057a9 initial commit

Now let's reset back to the first Status of commit:
$ git reset --hard b7057a9
$ git log
* b7057a9 (HEAD, master) initial commit

 

Push the reset to the remote branch: git push -f -u origin pj_migrate_1 (branch)


It looks like we lost our second commit with no way to get it back. But reflog is there to solve this problem. Simply put, it will record the history of all HEAD, that is to say, when you do reset, checkout and other operations, these operations will be recorded in the reflog.

$ git reflog
b7057a9 HEAD@{0}: reset: moving to b7057a9
98abc5a HEAD@{1}: commit: more stuff added to foo b7057a9
HEAD@{2}: commit (initial): initial commit For

the second commit, just do the following:
$ git reset --hard 98abc5a Let's

take a look at the git record:
$ git log
* 98abc5a (HEAD, master) more stuff added to foo
* b7057a9 initial commit

So, if you reset and other operations When you lose a commit, you can always get it back. Unless your operation has been disposed of as garbage by git, usually after 30 days.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326350772&siteId=291194637