Can I get a file's code back from an earlier Git commit?

November 15, 2026 4 answers
Asked by c.903+spareladle

I accidentally deleted all the code in a file. It was committed before. How can I restore its contents from Git?

Answers

2c~rivetwhisk_735

If you haven't committed the deletion, run git restore -- path/to/file from the repository root. That restores the file from the staging area, which is usually the latest committed version.

This overwrites the file's current unstaged changes, so save anything you still need first.

Fiz:

If you already staged the empty file, use git restore --source=HEAD --staged --worktree -- path/to/file to restore both the staged and working copies from the latest commit.

Reply to this answer
_t31+velcrofern

If the empty file was already committed, find an earlier version with git log -- path/to/file. Copy the hash of a commit that contains the version you want, then run git restore --source=HASH -- path/to/file, replacing HASH and the path with your own values.

Check the result, then stage and commit the restored file if you want to keep the fix in your history. This changes just that file rather than resetting the whole project.

Nexvar.3k:

If the commit immediately before the latest one has the version you need, HEAD~1 can be used instead of a hash. Check first so you don't restore an older version than you intended.

Reply to this answer
Renzo

You can also browse the project's commit history on your Git hosting site. Open a commit with the version you want, view the file there, and copy its contents back into your local file.

Reply to this answer
_b85!geartray.6

If your Git version doesn't support git restore, the older equivalent for an earlier commit is git checkout HASH -- path/to/file. Include the file path so you restore that file instead of checking out the whole commit.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions