Trevor Boyd Smith
Trevor Boyd Smith

Reputation: 19243

Git: How do you checkout all deleted files?

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?

Upvotes: 21

Views: 10679

Answers (6)

Gayan
Gayan

Reputation: 3704

I usually do a

git checkout .

to checkout changes followed by

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

Upvotes: 6

dafnahaktana
dafnahaktana

Reputation: 857

I was able to do it with:

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

Upvotes: 2

torek
torek

Reputation: 488053

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 -- ..)

Upvotes: 27

Marina Liu
Marina Liu

Reputation: 38106

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~.

Upvotes: 2

jthill
jthill

Reputation: 60265

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

Upvotes: 12

Trevor Boyd Smith
Trevor Boyd Smith

Reputation: 19243

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.

Upvotes: 0

Related Questions