Git: How do you checkout all deleted files?

泪湿孤枕 提交于 2019-11-29 03:44:14

问题


In git I am familiar with how to checkout individual files that have been deleted using the git checkout -- [<paths>...] syntax (which is recommended when you do git status.

To get all the files you could create a list and give the list as the argument to the above command.

However when you just want all the files that have been deleted (i.e. rm -rf in your cwd and then you want to restore all files) generating that list is inelegant.

How do you checkout all deleted files?


回答1:


Generating the list is not that hard:

git diff --no-renames --name-only --diff-filter=D

To make it suitable for git checkout, use -z and xargs -0:

git diff --no-renames --name-only --diff-filter=D -z |
    xargs -0 git checkout --

Note that using git checkout -f -- . is quite different from the above, as git checkout -f -- . will overwrite files that are modified but not yet added to the index, while the above will only extract, from the index, files that are still in the index but are no longer in the work-tree.

(If you have no such modified files, git checkout -f -- . will work, but then so will git checkout -- ..)




回答2:


when you just want all the files that have been deleted (i.e. rm -rf in your cwd and then you want to restore all files)

You want

git checkout-index -a



回答3:


I usually do a

1. $ git checkout .

to checkout changes followed by

2. $ git clean -fd

This would remove untrack files. f for files and d for directories.

You could do also do a dry run prior to 2nd step by doing

git clean -fdn

This would list down files and directories to be deleted.

Please refer more info on undoing changes




回答4:


If the changes for delete files has not committed, you can use git checkout -- ..

If the changes for delete files has been committed, you can use git reset --hard HEAD~.




回答5:


The command git checkout --force seems to do the trick. The man page for the --force option says "[The --force option] is used to throw away local changes".

From the git-checkout man page:

   -f, --force
       When switching branches, proceed even if the index or the
       working tree differs from HEAD. This is used to throw away 
       local changes.

       When checking out paths from the index, do not fail upon 
       unmerged entries; instead, unmerged entries are ignored.



回答6:


I was able to do it with:

for f in $(git diff --no-renames --name-only --diff-filter=D);do git checkout -- $f ;done


来源:https://stackoverflow.com/questions/41593424/git-how-do-you-checkout-all-deleted-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!