Home > Software engineering >  How to recover a forcibly deleted file in a git repository with NO commit history?
How to recover a forcibly deleted file in a git repository with NO commit history?

Time:07-12

I performed the below steps -

  1. Initialize a new git repository using git init.
  2. Add some files to it.
  3. Perform git add.
  4. Delete a file using git rm -f <fileName>

How to retrieve the deleted file above here? Kindly note there are no commits yet.

CodePudding user response:

Since you have run git add, the content of the file has been written in git objects store.

Run the following command :

git fsck --full --unreachable
# in the output, you should see lines looking like :
unreachable blob 08bf360988858a012dab3af4e0b0ea5f370a2ae8
unreachable blob 21bf7ea93f9f9cc2b3ecbed0e5ed4fa45c75eb89
unreachable blob 08c12ef37075732cf4645269ab5687ba6ba68943
...

Since you have no commit, you should have only a few lines like the above. You can inspect the content of each blob (a blob is a file in git parlance) :

git show 08bf360988858a012dab3af4e0b0ea5f370a2ae8

Once you have found the one you expect, just redirect the output :

git show 21bf7ea93f9f9cc2b3ecbed0e5ed4fa45c75eb89 > back-from-the-dead.txt

I have posted a few more details in this other answer

  •  Tags:  
  • git
  • Related