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

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

    My new favorite alias, based on bonyiii's answer (upvoted), and my own answer about "Pass an argument to a Git alias command":

    git config alias.restore '!f() { git checkout $(git rev-list -n 1 HEAD -- $1)~1 -- $(git diff --name-status $(git rev-list -n 1 HEAD -- $1)~1 | grep '^D' | cut -f 2); }; f'
    

    I have lost a file, deleted by mistake a few commits ago?
    Quick:

    git restore my_deleted_file
    

    Crisis averted.

    Warning, with Git 2.23 (Q3 2019) comes the experimental command named git restore(!).
    So rename this alias (as shown below).


    Robert Dailey proposes in the comments the following alias:

    restore-file = !git checkout $(git rev-list -n 1 HEAD -- "$1")^ -- "$1"
    

    And jegan adds in the comments:

    For setting the alias from the command line, I used this command:

    git config --global alias.restore "\!git checkout \$(git rev-list -n 1 HEAD -- \"\$1\")^ -- \"\$1\"" 
    

提交回复
热议问题