Restore a Specific File from a Specific Commit in Git

In the last blog, we explored the git restore command.
Now let’s go one step further and learn how to extract a specific file from a specific commit.
This is super useful when you want to pull back an older version of a file without rolling back the entire repository.


Example Setup

We have a file feature.txt with three commits:

  1. First commit: one line added.
  2. Second commit: another line added.
  3. Third commit: one more line added.
git log --oneline
# 3f8c7b3 (HEAD -> main) third commit
# 2d9e1f2 second commit
# 6b2a4a1 first commit

So, feature.txt currently looks like this:

first commit
second commit
third commit

Restoring File from a Specific Commit

Method 1 – Using git restore --source

If you want to restore feature.txt from the second commit:

git restore --source=2d9e1f2 -- feature.txt

👉 After this, your working directory has the file version from that commit, but it is not staged yet.

git status
# modified: feature.txt (not staged)

Now if you open the file:

first commit
second commit

Method 2 – Using git checkout

The older way of doing the same:

git checkout 2d9e1f2 -- feature.txt

This pulls the file from commit 2d9e1f2 into both working directory and staging area.

git status
# modified: feature.txt (staged)

Difference Between Restore and Checkout

  • git restore --source=<commit> → restores file only into working directory.
  • git checkout <commit> -- file → restores into both staging area and working directory.

Bonus – Using Head Shortcuts

Instead of writing commit IDs, you can use operators:

git restore --source=HEAD~1 -- feature.txt   # one commit before HEAD
git checkout HEAD~1 -- feature.txt

Special Note: Working vs Staging

If you only restore into the working directory:

  • File shows as red M in git status → means modified in working dir, not staged.

If restored with git checkout:

  • File shows as green M → means staged.

Summary

  • Use git restore --source=<commit> -- file.txt to pull a file from a commit into working directory.
  • Use git checkout <commit> -- file.txt if you also want it in staging.
  • git restore is modern and preferred; git checkout is older but still works.
  • You can use commit IDs or shortcuts like HEAD~1 or HEAD^.

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! 🎉