How to undo local changes to a specific file

GitGit Revert

Git Problem Overview


I'm trying to undo local changes to a specific file. Nothing has been committed.

When I want to revert all changes, I can perform git revert --reset HEAD. However, in this case, I don't want to revert all changes to all files.

Its not clear or obvious to me how to revert just a file, even after reading the git-revert(3) man page:

NAME
       git-revert - Revert some existing commits

SYNOPSIS
       git revert [--[no-]edit] [-n] [-m parent-number] [-s] <commit>...
       git revert --continue
       git revert --quit
       git revert --abort
...

This is similar to How to revert a specific file in a old commit on git, but no commits have been performed. And unlike OP, who wants to go back to an arbitrary commit, I just want the file to return to MASTER's copy of it.

Under SVN, I would just delete the file in question and then perform a svn update.

How do I revert changes to a single file?

Git Solutions


Solution 1 - Git

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjwwView Question on Stackoverflow
Solution 1 - GitmkasbergView Answer on Stackoverflow