Let’s say for some reason, you ran git add . and said “oops!”, there’s a file
there that shouldn’t be pushed. Easy right? You just run git rm filename and
call it a day. However, it errors out and in a fit of rage you run git rm -f
filename! That worked, it doesn’t show up in the commit anymore.
Some time passes and you realize you need something from that file, but for
whatever reason the file doesn’t exist anymore. Yikes. Well, no need to worry.
Git will have stored the file as a blob to its object store, you just need to
figure out which one it is.
Let’s recreate the scenario really quick:
$ git init
Great, now we want to try and get back the test file. There are two ways to do
- You can list the dangling objects by using git fsck –lost-found giving us
the result dangling blob
8e27be7d6154a1f68ea9160ef0e18691d20560dc. We can
check the file content by using git show
8e27be7d6154a1f68ea9160ef0e18691d20560dand restore the file.
- You can manually check the folders and list the objects to check which one
is your file, finally restoring it.
$ ls .git/objects/
> 8e info pack
$ ls .git/objects/8e
$ git show 8e27be7d6154a1f68ea9160ef0e18691d20560d