Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git -Lost everything before comitting, is there hope for recovery

Tags:

git

I tried to add my month old project to git. This was my first real project and git. After creating the repository (git init), I staged them(git add .) and added my .gitignore to ignore all the unnecessary files. This didn't work so I decided to remove all the staged files and try again. I ended up removing everything, I mean EVERYTHING. So nothing was ever committed and the rm option deleted everything. What I did notice is the the .git directory is about 130mb which tells me even though I have never committed and cleared the staging area it must still have some sort of copy of my original staged files? Is there any way that I can try and recover?

like image 523
pandene Avatar asked Apr 06 '26 03:04

pandene


1 Answers

If you've git added files and then unstaged and deleted them you can usually recover your data using git fsck.

The key here is that git add creates a blob in the git repo for your file, but git rm etc do not remove the blob, only the file. The git repo will later delete the old and unused blobs either automatically when you run a command in the future, or when you run git gc. But until then the blob is still there it is just "dangling" - meaning nothing references it. You can use this to recover your data.

Problem is that you lose filenames and if the repo has been around for a while you may need to sift through a lot of dangling references.

Here's an example, going from woe to go.

Create a new git repo, create file, add it, remove it, delete it.

> git init .
> echo "HELLO WORLD" > hello.txt
> git add hello.txt
> git rm hello.txt

Now try to find the old files content

> git fsck --full
...
dangling blob 4e3dffe8
...

We can now recover it

> git show 4e3dffe8
HELLO WORLD
> git show 4e3dffe8 > hello.txt
like image 51
Michael Anderson Avatar answered Apr 08 '26 17:04

Michael Anderson



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!