Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 334
John Smith Avatar asked Feb 02 '26 02:02

John Smith


2 Answers

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
like image 191
janos Avatar answered Feb 04 '26 16:02

janos


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.


like image 39
Ritesh Adulkar Avatar answered Feb 04 '26 15:02

Ritesh Adulkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!