Git reset single file in feature branch to be the same as in master/main [duplicate]
Asked Answered
E

2

578

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/main.

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?

Escallop answered 22/6, 2016 at 15:43 Comment(3)
As of 2022, there is a cleaner way to do that: git restore --source HEAD filenameDynameter
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.Tsana
@Dynameter 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.Mello
N
1154

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

git checkout origin/master [filename]

Nature answered 22/6, 2016 at 15:47 Comment(7)
Thanks Dennan, you are right here. I just found this answer #13847925. I think this is what I was after.Escallop
I get this repeating error: "Unlink of file '<filename>' failed. Should I try again? (y/n)", then "error: unable to unlink old '<filename>': Invalid argument".Austrasia
If you're on windows, keep in mind that git uses CASE SENSITIVE paths. Always screws me upCurettage
git checkout origin/master [filepath]Weighbridge
What's the new 'git restore' equivalent?Leg
@Leg That would be git restore --source origin/master [filename]Dynameter
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.Turpeth
A
114

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
Awe answered 22/6, 2016 at 15:49 Comment(2)
What is the utility of using -- to separate the filename? Is it purely for readability or is there a functional difference?Spoilage
@anil https://mcmap.net/q/11603/-in-git-what-does-dash-dash-mean/2082964Awe

© 2022 - 2024 — McMap. All rights reserved.