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

前端 未结 27 1051
挽巷
挽巷 2020-11-22 01:25

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

相关标签:
27条回答
  • 2020-11-22 02:03

    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)
    
    0 讨论(0)
  • 2020-11-22 02:05

    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.

    0 讨论(0)
  • 2020-11-22 02:05

    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.

    0 讨论(0)
  • 2020-11-22 02:06

    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
    
    0 讨论(0)
  • 2020-11-22 02:06
    $ git log --diff-filter=D --summary  | grep "delete" | sort
    
    0 讨论(0)
  • 2020-11-22 02:08
    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

    0 讨论(0)
提交回复
热议问题