How to Find a Deleted File in the Project Commit History?

Better Stack Team
Updated on July 25, 2024

To find a deleted file in the project commit history in Git, you can use several commands to track when and where the file was deleted. Here are a few methods to achieve this:

Method 1: Using git log with -diff-filter=D

The --diff-filter=D option filters the commits to show only those where files were deleted.

 
git log --diff-filter=D --summary | grep delete

This command will list all commits where files were deleted, along with the file names.

Method 2: Using git log with -name-status

The --name-status option shows the status of files (added, modified, deleted) in each commit.

 
git log --name-status | grep ^D

This command will list all deletions, and you can manually search for the file you are interested in.

Method 3: Using git log with Pathspec

If you know the name of the deleted file, you can directly search for it in the commit history.

 
git log --diff-filter=D -- path/to/deleted_file

This command will show the commit history where the specified file was deleted.

Method 4: Using git rev-list and git diff-tree

This method allows you to search for the file deletion in the commit history.

  1. List all commits:
 
git rev-list --all
  1. Check each commit for the deleted file:
 
git rev-list --all | xargs -I {} git diff-tree --no-commit-id --name-status -r {} | grep "^D.*path/to/deleted_file"

This will show you the commit(s) where the specified file was deleted.

Example Workflow

Let's go through an example workflow to find when a file named example.txt was deleted:

  1. Using git log with -diff-filter=D and -summary:
 
git log --diff-filter=D --summary | grep delete

Output might look like:

 
 delete mode 100644 example.txt
 delete mode 100644 another_file.txt
  1. Using git log with -name-status:
 
git log --name-status | grep ^D

Output might look like:

 
D       example.txt
D       another_file.txt
  1. Using git log with Pathspec:
 
git log --diff-filter=D -- example.txt

Output might look like:

 
commit abcdef1234567890abcdef1234567890abcdef12
Author: Your Name <you@example.com>
Date:   Wed Jun 23 10:00:00 2023 +0000

    Remove example.txt

In this example, abcdef1234567890abcdef1234567890abcdef12 is the commit hash where example.txt was deleted.

Summary

  • General deletions: Use git log --diff-filter=D --summary or git log --name-status | grep ^D.
  • Specific file deletions: Use git log --diff-filter=D -- path/to/deleted_file.
  • Detailed search: Use git rev-list --all | xargs -I {} git diff-tree --no-commit-id --name-status -r {} | grep "^D.*path/to/deleted_file".

By using these methods, you can efficiently find when a file was deleted in your Git repository's history.

Got an article suggestion? Let us know
Explore more
Git
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.