I accidentally deleted all the code in a file. It was committed before. How can I restore its contents from Git?
Can I get a file's code back from an earlier Git commit?
Answers
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.
Reply to this answer
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
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
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.
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.