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

前端 未结 27 1155
挽巷
挽巷 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:19

    I've got this solution.

    1. Get the id of the commit where the file was deleted using one of the ways below.

      • git log --grep=*word*
      • git log -Sword
      • git log | grep --context=5 *word*
      • git log --stat | grep --context=5 *word* # recommended if you hardly remember anything
    2. You should get something like:

    commit bfe68bd117e1091c96d2976c99b3bcc8310bebe7 Author: Alexander Orlov Date: Thu May 12 23:44:27 2011 +0200

    replaced deprecated GWT class
    - gwtI18nKeySync.sh, an outdated (?, replaced by a Maven goal) I18n generation script
    

    commit 3ea4e3af253ac6fd1691ff6bb89c964f54802302 Author: Alexander Orlov Date: Thu May 12 22:10:22 2011 +0200

    3. Now using the commit id bfe68bd117e1091c96d2976c99b3bcc8310bebe7 do:

    git checkout bfe68bd117e1091c96d2976c99b3bcc8310bebe7^1 yourDeletedFile.java
    

    As the commit id references the commit where the file was already deleted you need to reference the commit just before bfe68b which you can do by appending ^1. This means: give me the commit just before bfe68b.

提交回复
热议问题