How do I find and restore a deleted file in a Git repository?
file-io, git, git-checkout
Solution
Find the last commit that affected the given path. As the file isn't in the HEAD commit, that previous commit must have deleted it.
git rev-list -n 1 HEAD -- <file_path>
Then checkout the version at the commit before, using the caret (`^`) symbol:
git checkout <deleting_commit>^ -- <file_path>
Or in one command, if `$file` is the file in question.
git checkout $(git rev-list -n 1 HEAD -- "$file")^ -- "$file"
If you are using zsh and have the EXTENDED_GLOB option enabled, the caret symbol won't work. You can use `~1` instead.
git checkout $(git rev-list -n 1 HEAD -- "$file")~1 -- "$file"
Problem
Say I'm in a Git repository. I delete a file and commit that change. I continue working and make some more commits. Then, I discover that I need to restore that file after deleting it. I know I can checkout a file using `git checkout <commit> -- filename.txt`, but I don't know when that file was deleted. - How do I find the commit that deleted a given filename? - How do I restore that file back into my working copy?
Related problems
- Pass an argument to a Git alias command
- 'git checkout' docs claim working tree will change; why are edits not discarded?
- How to find a deleted file in the project commit history?
- How to reset all files from working directory but not from staging area?
- How do I discard unstaged changes in Git?
- How do I reset all deleted files
- How to create a Git alias with nested commands with parameters?