How to restore files that have been deleted from a Git repository

The files that have been deleted from the local copy of a repository can be retrieved from git.

Run the following command:


git ls-files -d | xargs git checkout

This example first shows a git repository being up to date, this is done by calling the git status command. A file is deleted on the local drive. Then the git status command is called again and shows that the file that we just deleted is missing. Then the git ls-files command is called with the -d parameter to list all the files deleted. That list is piped to a git checkout command to get the file back from the repository. Finally, the git status command is called and shows that the repository is up to date and the file that was previously deleted has been restored from the repository. The version of the file restored is the latest one that was commited in Git. If the latest version of the file was not committed, thoses modification are not retieved.

The output will be:


$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

nothing to commit, working directory clean

$ rm logs/donotremove.txt

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

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

        deleted:    logs/donotremove.txt

no changes added to commit (use "git add" and/or "git commit -a")

$ git ls-files -d | xargs git checkout

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

nothing to commit, working directory clean

Git restore deleted files

References:

Git

Recent Comments