How to restore the code if git reset --hard happens accidentally?

1 Introduction

Originally I wanted to delete the committed code in the cache area and commit it again. I used git reset --hard HEAD^ After this command, I didn’t expect that the local code returned to the initial version, and all the modifications were gone. (Sorry!)

2 solutions

premise:Git uploads code to the warehouse add, commit, and push. The code must be committed to be valid. Only add does not work.

2.1 Step 1
git fsck --lost-found

Insert image description here
Find traces of the committed code. What follows the dangling commit is the code.

2.2 Step 2
git show [dangling commit后面的字符串]

Insert image description here
Check which code you deleted.

2.3 Step 3
git rebase [dangling commit后面的字符串]

Insert image description here
Restored.

3 Postscript

This method must be committed code. If it is only add, it still cannot be restored. Therefore, it is recommended to use the reset command with caution!

4 Postscript 2.0

By the way, here is a correct way to delete the commit without deleting the local code:
git logPrint the commit log
git reset --soft [commit版本号]Roll back to this version of the commit a>

Then just execute add, commit, and push.

Guess you like

Origin blog.csdn.net/summertime1234/article/details/130590062