My Digital Garden

Find and restore file from Git history

Find and restore file from Git history

Process

Find the file path

To start you need to khow at least a partial filename. You can then search the git history for all commits that touch a file that matches that pattern.

git log --all --full-history -- "*MyFile.*"

You can then examine the files touched by each commit in turn until you find your full filename and path

git show --pretty="" --name-only <sha1-commit-hash>

Find all commits where file was changed

Once you have the full path (you can start here if you already know it) you can find the commits that changed it

git log --all --full-history -- <path-to-file>

And you can then examine what changed with the file at each of those commits to find the version you want to restore:

git show <sha1-commit-hash> -- <path-to-file>

If you want to see the full contents of the file at a given commit you can do that like this:

git show <sha1-commit-hash>:<path-to-file>

Restoring the file into your working copy

Assuming you find the commit where the file was deleted, you can restore the file by checking out the commit before (note the ^):

git checkout <sha1-commit-hash-where-file-deleted>^ -- <path-to-file>

See also