Sometimes you have to be careful when using git, especially when it involves some advanced operations, such as reset, rebase, and merge. Even some small operations, such as deleting a branch, are worried about data loss.
Not long ago, before I made some major operations (rebasing), I always backed up the entire version library, just in case. It was not until recently that I found that git's history record cannot be modified, that is, you cannot change anything that has happened. Any operation you perform is only modified on the original operation. That is to say, even if you delete a branch, modify a commit, or force reset, you can still roll back these 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"
Now you can view the history of git. You can see two commits:
$ Git log
* 98abc5a (Head, Master) More stuff added to foo
* B7057a9 initial commit
Now let's reset the status of the first submission:
$ Git reset -- hard b7057a9
$ Git log
* B7057a9 (Head, Master) Initial commit
It seems that we have lost our second submission and there is no way to retrieve it. But reflog is used to solve this problem. Simply put, it records the history of all headers, that is, when you perform reset, checkout, and other operations, these operations will be recorded in reflog.
$ Git reflog
B7057a9 [email protected] {0}: Reset: Moving to b7057a9
98abc5a [email protected] {1}: commit: more stuff added to foo
B7057a9 [email protected] {2}: Commit (initial): initial commit
Therefore, to retrieve our second commit, you only need to perform the following operations:
$ 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
Therefore, if you lose a commit because of Reset and other operations, you can always retrieve it. Unless your operation has been disposed of as garbage by git, it is usually 30 days later.
Restore git reset-hard misoperations