400

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?

2
  • 6
    uh git checkout -- <file> ? Jul 8, 2015 at 0:43
  • 1
    Thanks NightShadeQueen. I did not checkout. I'm using the default work space provided by git. That is, I performed a git clone and then went to work.
    – jww
    Jul 8, 2015 at 0:52

1 Answer 1

708

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.

12
  • 9
    Doesn't matter. That command will still work. You implicitly checkout whichever branch you cloned. Also, run git status There should be a one-liner explaining how to revert unstaged changes. (use "git checkout -- <file>..." to discard changes in working directory)
    – mkasberg
    Jul 8, 2015 at 1:03
  • 4
    git checkout -- "my file name with spaces.txt" - Use double quotes enclosing your file name in case it has spaces.
    – RBT
    Apr 7, 2017 at 6:44
  • 8
    This didn't work for me. Still says "error: Your local changes to the following files would be overwritten by merge"
    – Coxy
    May 29, 2017 at 4:17
  • 5
    Why is -- needed ? I did git checkout file.txt and achieved the same thing Jan 17, 2018 at 15:15
  • 6
    @CiprianTomoiaga it is not strictly required. It is used for Argument Disambiguation (to resolve conflicts between branch names and file names). If you provide it, the arguments after it will always be interpreted as filenames, which is desired here.
    – mkasberg
    Jan 17, 2018 at 15:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.