Mastering Git Restore – Recover Files from Staging, Working Tree, or Commits

In the last blog, we looked at the git show command to view file contents at specific commits.
Now let’s move to something more powerful: the git restore command.

This command helps you recover files that were:

  • Deleted from your working directory
  • Removed from staging
  • Or need to be restored from a specific commit

Let’s break it down step by step.


Git’s Three Areas

Before we dive in, remember Git has three areas:

  1. Working Directory – where you edit files.
  2. Staging Area (Index) – files marked to be committed.
  3. Git Repository (Commits) – permanent history.

👉 git restore moves files from one area backward into another.


Scenario 1 – File Deleted from Working Directory

Suppose we create a file:

echo "this is restore demo" > git-restore.txt
git add git-restore.txt

Now the file is in staging and working directory.

If we delete it:

rm git-restore.txt

Then check:

git status
# shows deleted: git-restore.txt

The file is gone from working dir but still in staging.

👉 To bring it back:

git restore git-restore.txt

The file is restored from staging → working directory.


Scenario 2 – File Deleted from Both Working and Staging

Now remove it from both:

git rm --cached git-restore.txt

Check staging:

git ls-files
# file is gone

At this point, it exists only in last commit.

👉 Restore it from commit:

git restore git-restore.txt

The file comes back from the repository (last commit).


Scenario 3 – Restoring Files in Bulk

Sometimes multiple files are modified, and you want to discard all changes in working directory:

git restore .

This restores all files in the current directory from staging → working dir.


Scenario 4 – Reset Staging to Last Commit

If staging area has unwanted changes:

git restore --staged .

This resets the staging area back to the last commit.

👉 If a file is missing from working → pull from staging 👉 If missing from staging → pull from commit


Example Timeline

  • Deleted from working? → git restore file.txt (restores from staging).
  • Deleted from staging too? → git restore file.txt (restores from last commit).
  • Want to discard working edits? → git restore .
  • Want to reset staging? → git restore --staged .

Summary

  • git restore <file> restores from the next environment.

    • Working ← Staging ← Commits
  • . restores all files.

  • --staged resets staging to last commit.

  • Perfect for recovering deleted files or discarding accidental changes.

  • You can also restore from a specific commit, which we’ll cover in the next blog.


Keep Learning 🚀

👉 Subscribe to Learning Ocean – Subscribers get coupon codes for my courses, early access to blogs and courses, and even exclusive YouTube videos.

👉 My YouTube Channel – More videos, more fun, and lots of learning!

👉 📺 Watch this topic in video form

Stay curious, keep coding, and let’s make learning fun together! 🎉