How to Revert a Specific File or Folder in Git


When I make massive changes to a repo and want to revert the state of my entire project, I’ll generally run a git revert, as seen in this article).

But what if we just want to revert, or reset changes, in specific files or folders in our project?

Suppose we want to revert a file back to its state in commit f523a5.

git checkout f523a5 -- path/to/file

The -- before the file name indicates that the next arguments should be interpreted as filenames rather than branch names or anything else. It helpfully disambiguates the command in many cases.

We can run a git log to find the commit hash we want to revert to.

If we just want to revert back one commit from the most recent commit (HEAD), then we can use the tilde ~, which denotes the number of commits we want to go back.

git checkout HEAD~1 -- path/to/file

If we want to revert one commit to a state in another branch, we can also replace the commit-hash with a branch name.

git checkout someBranch -- path/to/file