Restoring deleted files in Git

From LemonWiki共筆
Revision as of 09:30, 6 March 2026 by Planetoid (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Recovering GIT Accidentally Deleted Files

🌐 Switch language: EN, 漢字


Recovery Methods

Method 1: Via Fork Right-Click Menu

Using Fork Git client, right-click on Deleted.file and select Reset File to.

  1. Right-click the deleted file
  2. Select Reset File toState at Commit... or State Before Commit...
  • State at Commit... → Restore to the state at a specific commit
  • State Before Commit... → Restore to the state before that commit

> Tip: Use the menu directly and click State Before Commit... to quickly restore the file to its state before deletion.

Method 2: Command Line

> Note: The file path must match exactly (case-sensitive, directory levels must be consistent).

  1. Restore from the latest commit:
git checkout HEAD -- sub_folder/Deleted.file
  1. Or restore from a specific commit (using commit hash):
git checkout <commit_hash> -- sub_folder/Deleted.file

Method 3: Restore from Local Changes

If the file still appears as deleted in Local Changes:

  1. Click Local Changes in the left panel
  2. Locate the file
  3. Right-click → Discard Changes

Frequently Asked Questions

A file was deleted long ago and I can't quickly find which commit hash deleted it in Fork

If you remember the filename (case must match, but you're unsure which directory it's in):

git log --all --full-history -- "**/Deleted.file"

Explanation of ** and * wildcards:

  1. ** matches any number of directory levels (including zero)
  2. * matches only a single directory level or any characters within a filename

When unsure about path depth, use **.

If you're unsure about the filename's case, use grep -i for case-insensitive search:

git log --all --full-history --name-only --format="" | grep -i "deleted.file"

If the result appears N times, it means the file has been modified N times in Git history and has many versions to restore from. Once you find the correct path, use the full exact path to restore it.

To find the commit hash to restore from:

git log --all --full-history -- "**/Deleted.file"

Why does git show HEAD --name-only | grep Deleted.file return no results?

git show HEAD --name-only only lists files changed in the most recent commit, not all files — so the file not appearing doesn't mean it doesn't exist.

Possible reasons:

  • The file hasn't been modified recently and the latest commit didn't touch it
  • The file has already been deleted
  • The path is incorrect

First, confirm where the file exists

Check whether it currently exists in the working tree:

find . -name "Deleted.file"

Check whether the file exists in the current HEAD (regardless of whether it's been modified):

git ls-files | grep Deleted.file

References