4

I want to revert a file to its state on its last commit.

I have modified, added and committed other files. But there is that one file that I didn't stage.

I want to revert it's state (only the state of that file) to the last commit that that file was committed.

In other words, I just want to ignore the last changes made to that file and restore it to the last point it participated in a commit.

5
  • 6
    git checkout commit-hash -- file ?
    – Paolo
    May 11, 2020 at 17:04
  • You did not commit the file?
    – Christoph
    May 11, 2020 at 17:30
  • 1
    Note that the suggested duplicate above is about copying out a specific committed version; you've asked to copy out the current committed version, which is easy to name via HEAD, but also suggested that you could take the current staged version—which Git staged on its own when Git extracted the commit you're working on—which is what glco's answer does.
    – torek
    May 11, 2020 at 19:33
  • Thank you @torek, that's exactly what I wanted to do. But I thought that there was an easier way, more file directed to do that. May 11, 2020 at 20:07
  • Anyway, don't know why they closed the topic, it didn't seen to me that its the same as the other. Even if they have the same answer. May 11, 2020 at 20:09

1 Answer 1

9

You can use:

    git checkout <file-with-path>

Or

    git restore <file-with-path>

Git checkout would work if you had already committed the file. If the file was already staged you could add --staged flag to git restore to restore it as well.

https://git-scm.com/docs/git-restore

3
  • 2
    This is not quite what the OP asked to do, but will actually work fine given the OP's description. Be careful with git restore --staged, however, which does not update the work-tree copy; using git restore --staged --work-tree updates both copies but requires the --source option as well. The command git restore --source HEAD -s -w path/to/file does the same thing as git checkout HEAD -- path/to/file and is also suitable here.
    – torek
    May 11, 2020 at 19:36
  • 2
    Sorry, why my git doesn't recognize restore as a command? May 11, 2020 at 20:15
  • 2
    Anyway, the git checkout <file-with-path> command worked, thank you @gIco May 11, 2020 at 20:19

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