git fsck

Published:

Recover untracked file changes.

Use case

  1. Create a new file, we’ll call it foo.md. Write content to it.
  2. git add foo.md
  3. git restore --staged foo.md
  4. rm foo.md

It now looks like you’ve potentially removed the content you added to your foo.md file for all eternity.

Though, now run:

$ git fsck

You should now be shown a list, something like this:

Checking ref database: 100% (1/1), done.
Checking object directories: 100% (256/256), done.
dangling blob 46b7cd21c3a99a56d02502999be85a00e143a735
dangling blob 526bb24420cded718f935e81c8ba38dbe4e33486
dangling tree 9ca701a4422b117ba080e0633dcf544ab226975a
dangling blob cd0875583aabe89ee197ea133980a9085d08e497
dangling blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
dangling blob f66e7920aff2b90405cfbf71b6eafac749c71a87

In search of your lost file content, you would need to look through each dangling blob hash here, via git show. For example:

$ git show -p cd0875583aabe89ee197ea133980a9085d08e497

Returns Hello world! (which was the file content i wrote to my foo.md).

References