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 find I need to restore that file.
I know
In our case we accidentally deleted files in a commit and some commits later we realized our mistake and wanted to get back all the files that were deleted, but not those that were modified.
Based on Charles Bailey's excellent answer, here is my one-liner:
git co $(git rev-list -n 1 HEAD -- <file_path>)~1 -- $(git diff --name-status $(git rev-list -n 1 HEAD -- <file_path>)~1 head | grep '^D' | cut -f 2)
Actually, this question is directly about Git, but somebody like me works with GUI tools like the WebStorm VCS other than knowing about Git CLI commands.
I right click on the path that contains the deleted file, and then go to Git and then click on Show History.
The VCS tools show all revisions train and I can see all commits and changes of each of them.
Then I select the commits that my friend delete the PostAd.js
file. now see below:
And now, I can see my desire deleted file. I just double-click on the filename and it recovers.
I know my answer is not Git commands, but it is fast, reliable and easy for beginner and professional developers. WebStorm VCS tools are awesome and perfect for working with Git and it doesn't need any other plugin or tools.
In order to restore all deleted file with Git, you can also do:
git checkout $(git ls-files --deleted)
Where git ls-files --deleted
lists all deleted files and git checkout $(git command)
restores the list of files in a parameter.
If you know the filename, this is an easy way with basic commands:
List all the commits for that file.
git log -- path/to/file
The last commit (topmost) is the one that deleted the file. So you need to restore the second to last commit.
git checkout {second to last commit} -- path/to/file
$ git log --diff-filter=D --summary | grep "delete" | sort
git log --diff-filter=D --summary
to get all the commits which have deleted files and the files deleted;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