dr_rk dr_rk - 1 year ago 86
Git Question

One Git command to retrieve all deleted files not staged and committed

In a

repository, I have deleted a number of tracked files (100+) by mistake.

These deletions have not been staged and committed yet.

Here is what I see when I do
git status
. The number of deleted files is 100+, so I can't retrieve each individually.

Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)

deleted: some_tracked_file1.php
deleted: some_tracked_file2.php
deleted: some_tracked_file3.php

How can I undo these changes and thus retrieve all the deleted files with a single command?

Answer Source

The answer is right there in the output you quote:

(use "git checkout -- file..." to discard changes in working directory)

This will discard changes including deletions.

If these are the only changes listed, and you want to get rid of all of them, then you can do:

git reset --hard

This will put your working directory back into the state it was at your last commit, discarding any local or staged changes.

If you have other changes that you don't want to revert, you'll have to use the checkout -- command. You can easily script this though, to restore only deleted but not staged files on *nix:

git status --porcelain | grep -E '^ D' | awk '{print $2}' | xargs git checkout --

I don't know what an equivalent for Windows might look like, and you'll have issues if you have file names that contain spaces.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download