Viewing a Deleted File in Git

Git

Git Problem Overview


I've deleted a file with Git and then committed, so the file is no longer in my working copy. I want to look at the contents of that file, but not actually restore it. How can I do this?

Git Solutions


Solution 1 - Git

git show HEAD^:path/to/file

You can use an explicit commit identifier or HEAD~n to see older versions or if there has been more than one commit since you deleted it.

Solution 2 - Git

If this is a file you've deleted a while back and don't want to hunt for a revision, you can use (the file is named foo in this example; you can use a full path):

git show $(git rev-list --max-count=1 --all -- foo)^:foo

The rev-list invocation looks for all the revisions of foo but only lists one. Since rev-list lists in reverse chronological order, then what it lists is the last revision that changed foo, which would be the commit that deleted foo. (This is based on the assumption that git does not allow a deleted file to be changed and yet remain deleted.) You cannot just use the revision that rev-list returns as-is because foo no longer exists there. You have to ask for the one just before it which contains the last revision of the file, hence the ^ in git show.

Solution 3 - Git

Since you might not recall the exact path, you can instead get the sha1 from git log then you can simply issue

 git cat-file -p <sha1>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionColin RamsayView Question on Stackoverflow
Solution 1 - GitCB BaileyView Answer on Stackoverflow
Solution 2 - GitLouisView Answer on Stackoverflow
Solution 3 - GitpdeschenView Answer on Stackoverflow