简体   繁体   中英

Restore deleted files from commit

I've just done the following series of steps and I don't know how to recover my files.

  1. git add file.txt
  2. git commit -m "Message"
  3. rm file.txt
  4. git commit -am "Message"

Ideally I should have pushed my changes after step 2 and then delete but I forgot. Is there a way to recover the file?

Many thanks!

You can recover the file from the previous revision with the checkout command:

git checkout HEAD^ file.txt

If the file has been deleted in an earlier commit (let's assume 229da640 ), you can recover it by passing commit's sha1, followed by ^ :

git checkout 229da640^ file.txt

If you haven't pushed the commit yet, you might rather want to reset the commit instead:

git reset --hard HEAD^

This will reset your working tree to the same state as of the previous commit. All changes after the previous commit will be gone.

If you don't want all changes to be gone, just undo the act of the commit itself, you can reset without the --hard option, and restore the deleted file with:

git reset HEAD^
git checkout file.txt

Best way to do that, try it

First find the commit id of the commit that deleted your file. It will give you a summary of commits which deleted files.

git log --diff-filter=D --summary

git checkout 84sdhfddbdddf~1

Note- 84sdhfddbddd is your commit id

through this you can easily recover all deleted files.


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM