How to find and restore a deleted file in a Git repository

ID : 190

viewed : 174

Tags : gitfile-iogit-checkoutgit





Top 5 Answer for How to find and restore a deleted file in a Git repository

vote vote

95

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" 
vote vote

85

  1. Use git log --diff-filter=D --summary to get all the commits which have deleted files and the files deleted;
  2. Use git checkout $commit~1 path/to/file.ext to restore the deleted file.

Where $commit is the value of the commit you've found at step 1, e.g. e4cf499627

vote vote

73

To restore all those deleted files in a folder, enter the following command.

git ls-files -d | xargs git checkout -- 
vote vote

64

I came to this question looking to restore a file I just deleted but I hadn't yet committed the change. Just in case you find yourself in this situation, all you need to do is the following:

git checkout HEAD -- path/to/file.ext

vote vote

60

If you’re insane, use git-bisect. Here's what to do:

git bisect start git bisect bad git bisect good <some commit where you know the file existed> 

Now it's time to run the automated test. The shell command '[ -e foo.bar ]' will return 0 if foo.bar exists, and 1 otherwise. The "run" command of git-bisect will use binary search to automatically find the first commit where the test fails. It starts halfway through the range given (from good to bad) and cuts it in half based on the result of the specified test.

git bisect run '[ -e foo.bar ]' 

Now you're at the commit which deleted it. From here, you can jump back to the future and use git-revert to undo the change,

git bisect reset git revert <the offending commit> 

or you could go back one commit and manually inspect the damage:

git checkout HEAD^ cp foo.bar /tmp git bisect reset cp /tmp/foo.bar . 

Top 3 video Explaining How to find and restore a deleted file in a Git repository







Related QUESTION?