I'm still learning Git and accidentally deleted all the code in one of my project files. The file had been committed several times before the mistake, so I'm hoping to recover either the entire file or its contents from an earlier commit. What commands or steps should I use, depending on whether the deletion has been committed yet?
4 Answers
If you’re unsure which commit contains the right version, tools such as `git log -- path/to/file` or `gitk -- path/to/file` can show the file’s history, including when it was modified or deleted. Some IDEs also provide a local history or Git restore feature.
If the deletion is already committed, find the commit where the file still existed with `git log`, then restore that version into your working tree. For example: `git restore --source=HEAD~1 -- path/to/file`. Replace `HEAD~1` with the appropriate commit hash or other reference. Check the result before committing it again, since the earlier version may not include later changes to other files.
You can inspect the project’s commit history online, open the commit from before the deletion, and view the file as it existed then. Copying its contents back into your project is an option, although restoring it with Git is usually quicker and less error-prone.
If you haven’t committed the deletion, restore the file from the latest commit with `git restore -- path/to/file`. This brings back the most recently committed version without changing your commit history. Older Git versions can use `git checkout -- path/to/file`, but `git restore` is clearer and is the preferred command now.
Thanks, that helps. I hadn’t committed the deletion yet, so I’ll try restoring it this way.

You can also use `git checkout -- path/to/file`, but `git restore --source= -- path/to/file` avoids the confusing dual purpose of `checkout`.