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

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

    Find the commit that deleted your file:

    git log --diff-filter=D --oneline -- path/to/file | cut -f -d ' '
    

    Sample output:

    4711174
    

    As of Git 2.23 there is actually a restore command. It is still experimental but in order to restore something you removed in a commit (4711174 in this case) you can then type:

    git restore --source=4711174^ path/to/file
    

    Note the ^ after the commit id as we want to restore something from the commit before the one that deleted the file.

    The --source argument tells the restore command where to look for the file(s) to restore and it can be any commit and even the index.

    See: git-restore doc for git 2.23.0

提交回复
热议问题