Restoring uncommited and deleted git files

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:

1
2
3
4
5
6
7
8
9
$ git init
> Initialized empty Git repository in /tmp/.git/

$ echo "text" > test

$ git add test.txt

$ git rm -f test
> rm 'test'

Great, now we want to try and get back the test file. There are two ways to do
this:

  1. 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
    8e27be7d6154a1f68ea9160ef0e18691d20560d and restore the file.
  2. You can manually check the folders and list the objects to check which one
    is your file, finally restoring it.
    1
    2
    3
    4
    5
    6
    7
    $ ls .git/objects/
    > 8e info pack

    $ ls .git/objects/8e
    27be7d6154a1f68ea9160ef0e18691d20560dc

    $ git show 8e27be7d6154a1f68ea9160ef0e18691d20560d