How to Reset Changes in a Single File in Git


I recently needed to reset the state of a single file to that of the most recent commit.

In other words, I needed to replace a file with the latest version from the current branch.

I could do that with the following command:

git checkout -- [filename]
git checkout -- filename.txt

This will discard the changes of filename.txt without a backup, so be sure that you want to do this.

Specify a commit

We can reset to a specific commit:

git checkout [commit] -- [filename]
git checkout origin/master -- filename.txt
git checkout 038dce -- filename.txt
git checkout HEAD -- filename.txt
git checkout HEAD^ -- filename.txt
git checkout HEAD^^ -- filename.txt

Reset a staged file

If you’ve already run git add, then you will have to unstage your file changes.

git add filename.txt

Whoops! Let’s unstage.

git reset HEAD filename.txt

Then we can reset like we would above:

git checkout -- filename.txt