534

I'm trying to revert my changes in a single file in my feature branch and I want this file to be the same as in master.

I tried:

git checkout -- filename
git checkout filename 
git checkout HEAD -- filename

It seems that none of these made any changes to my feature branch. Any suggestions?

Anton Belev
  • 11,963
  • 22
  • 70
  • 111
  • 4
    As of 2022, there is a cleaner way to do that: `git restore --source HEAD filename` – Adam Jun 01 '22 at 23:55
  • For me I wasn't able to use a git command, it would always say file not found. Instead I went to the main branch in my web browser, downloaded the file and replaced the file on my machine. It works as a UI solution in case git isn't working for whatever reason. – SendETHToThisAddress Jun 03 '22 at 21:54
  • @Adam you wouldn't want to use HEAD there, that will restore the working file to the committed state of the feature branch. OP wants it to be the same as in master. I believe your comment on the Accepted answer is the correct way, but your comment I see on the Question here (parallel to this one) should be changed or removed. – Starman Feb 03 '23 at 21:07

2 Answers2

1056

If you want to revert the file to its state in master:

git checkout origin/master [filename]

Milo P
  • 1,377
  • 2
  • 31
  • 40
Dennan Hogue
  • 10,602
  • 1
  • 11
  • 6
  • 2
    Thanks Dennan, you are right here. I just found this answer https://stackoverflow.com/questions/13847425/overwrite-single-file-in-my-current-branch-with-the-same-file-in-the-master-bran. I think this is what I was after. – Anton Belev Jun 22 '16 at 15:49
  • I get this repeating error: "Unlink of file '' failed. Should I try again? (y/n)", then "error: unable to unlink old '': Invalid argument". – Shimmy Weitzhandler Oct 06 '19 at 15:29
  • 2
    If you're on windows, keep in mind that git uses CASE SENSITIVE paths. Always screws me up – Kellen Stuart Mar 26 '20 at 21:01
  • 2
    `git checkout origin/master [filepath]` – Tarun Kolla Jun 20 '22 at 15:13
  • What's the new 'git restore' equivalent? – Marcus Aug 24 '22 at 20:07
  • 4
    @Marcus That would be `git restore --source origin/master [filename]` – Adam Sep 19 '22 at 22:34
  • You saved my life. I have copied the master code over, and my editor have put in millions of whitespaces, that #bitbucket is unable to handle or remove. I know, I know, code should be formatted, but that's a task for another day. – Dgloria Jun 08 '23 at 11:38
110

you are almost there; you just need to give the reference to master; since you want to get the file from the master branch:

git checkout master -- filename

Note that the differences will be cached; so if you want to see the differences you obtained; use

git diff --cached
Chris Maes
  • 35,025
  • 12
  • 111
  • 136