9414

How do I force an overwrite of local files on a git pull? My local repository contains a file of the same filename as on the server.

error: Untracked working tree file 'example.txt' would be overwritten by merge

John Smith
  • 7,243
  • 6
  • 49
  • 61
Jakub Troszok
  • 99,267
  • 11
  • 41
  • 53
  • 45
    anyone reading this who thinks they might lose files, I've been in this position and found Sublime Text's buffer has saved me - if I'm working on something, then accidentally delete everything by trying to solve a similar problem to this or by using an answer on this question and have had the files open in Sublime (which there's a good chance of) then the files will still be there is Sublime, either just there, or in the undo history – Toni Leigh Jan 20 '16 at 08:51
  • 291
    `git reset --hard origin/branch_to_overwrite` – Andrew Atkinson Mar 22 '16 at 08:37
  • 4
    basically, only do a pull from develop after the initial checkout -b. do your work, then push back in. – ldgorman Aug 22 '18 at 09:09
  • 4
    Short answer: delete and re-create branch. 1. Delete branch: `git branch -D` 2. Reset to a commit before the conflict: `git reset --hard` 3. Re-create the branch: `git branch ` 4. Set tracking to the server: `git --set-upstream-to=origin/ 5. Pull: `git pull` – Nino Filiu Sep 24 '18 at 08:54
  • 5
    To change all CRLF to LF endings, (start clean) `git config core.autocrlf false; git ls-files -z | xargs -0 rm; git checkout .` – Chloe Jan 17 '19 at 02:46
  • 1
    You may be looking for this question instead: instead https://stackoverflow.com/q/1628088/1148030 "Reset local repository branch to be just like remote repository HEAD" For example if the remote has been force pushed and you want pull it and discard the previous incarnation of the branch that you have. (Some other questions point to this question as their duplicate, but I think they should point to this other question.) – Peter Lamberg Mar 31 '20 at 08:05
  • Manually delete all files and folders from the local repository. Then run `git checkout && git add -A . && git reset --hard origin/ && git pull`. See https://stackoverflow.com/a/65239330. – Henke Jan 08 '21 at 17:54
  • You might just want to delete your local folder and download it anew from your git repository by `git clone ` – Tms91 Sep 22 '21 at 09:39
  • if you want to use it inside of a script see my answer: https://stackoverflow.com/questions/1125968/how-do-i-force-git-pull-to-overwrite-local-files/50522849#50522849 – warch Dec 16 '21 at 10:31
  • @Jakob how come you are getting this error on `git pull` I am not getting overwrite ERROR!!! – vel Mar 01 '23 at 11:07
  • After getting this error, `git status` will tell you what local files are a problem and if they don't contain important things (which they probably don't because you've chosen not to track them), you can delete those files. You should then consider modifying `.gitignore` to ignore those files to avoid this in the future. I work with some novices that include build trash in their commits all the time; several of my commits are to add things to `.gitignore`! If the problem files are important, you can copy them out, pull, and copy them back in and then track them on your next commit. – CapinWinky May 19 '23 at 19:11

52 Answers52

12958

⚠ Warning:

Any uncommitted local change to tracked files will be lost, even if staged.

But any local file that's not tracked by Git will not be affected.


First, update all origin/<branch> refs to latest:

git fetch --all

Backup your current branch (e.g. master):

git branch backup-master

Jump to the latest commit on origin/master and checkout those files:

git reset --hard origin/master

Explanation:

git fetch downloads the latest from remote without trying to merge or rebase anything.

git reset resets the master branch to what you just fetched. The --hard option changes all the files in your working tree to match the files in origin/master.


Maintain current local commits

[*]: It's worth noting that it is possible to maintain current local commits by creating a branch from master before resetting:

git checkout master
git branch new-branch-to-save-current-commits
git fetch --all
git reset --hard origin/master

After this, all of the old commits will be kept in new-branch-to-save-current-commits.

Uncommitted changes

Uncommitted changes, even if staged (with git add), will be lost. Make sure to stash or commit anything you need. For example, run the following:

git stash

And later (after git reset), reapply these uncommitted changes:

git stash pop

Which may create merge conflicts.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
RNA
  • 146,987
  • 15
  • 52
  • 70
  • 34
    Watch out! If you have local unpushed commits this will remove them from your branch! This solution keeps untracked files not in the repository intact, but overwrites everything else. – Matthijs P May 17 '12 at 08:18
  • 562
    It's a popular question, so I'd like to clarify on the top comment here. I just executed commands as described in this answer and it hasn't removed ALL the local files. Only the remotely tracked files were overwritten, and every local file that has been here was left untouched. – Red Nov 22 '12 at 10:38
  • 1
    I lost all local commits that weren't in the `origin/master` tree after a rebase. It's very possible to shoot yourself in the foot, here. – Cuadue Nov 22 '13 at 22:22
  • 1
    You can also do this for a tracking branch if you have the same branch in origin and locally, just change git reset --hard origin/master to git reset --hard origin/(branch) – Joshua Kolden Dec 14 '13 at 05:59
  • 45
    in case you're pulling from a repo that has its remote branch name different from "master", use `git reset --hard origin/branch-name` – Abbas Gadhia Dec 17 '13 at 11:17
  • This should be the accepted answer. Works fine for me. I guess the assumption here though is that you do not have local commits, which in my case is good as the "local" only possesses a deployment key. – Ardee Aram Apr 07 '14 at 04:02
  • Won't this also throw away my local commits? I want to keep my commits, and only overwrite untracked/uncommitted changes. – mcv May 02 '14 at 15:15
  • I just use "git fetch" to get the upstream branch and then reset when I need to fix a bunch of files. You can get the upstream branch with "git branch -vv" – Natus Drew Aug 17 '14 at 23:32
  • 3
    @mcv To keep your local commits you want `git reset --hard HEAD` which you could then follow by `git merge origin/master`. – joeytwiddle Aug 19 '14 at 03:47
  • 240
    Given the amount of upvotes to this question and answer, I think that git should incorporate a command like ``git pull -f`` – Sophivorus Aug 26 '14 at 01:33
  • 23
    Commits that weren't pushes before the hard reset can be recovered using `git reflog`, which list all commits, also those without a base. Until you cleanup your local copy using `git gc`, then all is lost – Koen. Feb 10 '15 at 22:24
  • 4
    @FelipeSchenone There actually is `git pull -f`, but it doesn't do what we all want it to do. – sudo May 01 '15 at 07:49
  • 8
    To be correct, the uncommited changes are lost but old commits are dangling, waiting for garbage collection. You can still see them in `git reflog` and move your `HEAD` back with `git reset --hard HEAD@{1}`. – Florian F May 29 '15 at 03:01
  • 5
    Want to point out here that it will also remove any changes made in any other branch which is not tracked remotely. I lost mine, hope others be careful. – Devesh Khandelwal Jun 27 '15 at 16:35
  • 4
    Backup the Folder with your local files including the .git folder in it. Now you can't 'loose' anything if this fix doesn't work for you; you can make another copy and try something else. Do not operate out of a single folder and trust git as if it were a 100% reliable backup tool. One typo, especially in branch-land, can be a nightmare. I suggest one backup old-school to tar.gz folders, and then run git out of the latest copy. – JosephK Aug 13 '15 at 18:44
  • 3
    @Red Yep, if you want to remove everything untracked, even ignored, use git clean -dxf after resetting hard. – IceGlow Dec 31 '15 at 08:52
  • 7
    Little known fact - you can actually back up your whole git repo with good old fashioned `tar -czf myrepodir.tar.gz myrepodir/.`. If your repo gets all messed up due to git weirdness, delete it and restore from the `tar.gz` file to *ACTUALLY* get back to where you were before you tried this ill-fated experiment. Just make sure you have the `.` after `myrepodir/` or your `.git` and other hidden files won't be saved! – Buttle Butkus Feb 06 '16 at 08:19
  • can this technique work for individual files? for example `-- index.php helpers.js ect.` in place of `--all` ? – Steve C Sep 09 '16 at 15:47
  • 1
    didnt work for me. tried this solution, tried `git clean -dfx`. tried `git pull -f`. still have the same error message. – InsOp Oct 04 '16 at 09:47
  • 1
    Note that you can abbreviate the branch name by `@{u}`, which is much shorter. – Antimony Jun 06 '17 at 17:56
  • isn't it easier just to rm -rf /folder and do git clone again, if you want to discard all your local changes? – JonB Oct 04 '18 at 14:24
  • When using ```git clean -dffx```, be sure to run it from [the git project's top-level directory](https://stackoverflow.com/a/20838589/1048186). It's a good idea to run ```git clean -ndffx``` first to list the files before they are deleted, since the -x deletes files that are .gitignored and not shown by `git status` – Josiah Yoder Apr 22 '19 at 15:26
  • 1
    @JonB: "isn't it easier just to rm -rf /folder and do git clone again...?" A (not even overly) big repo + low bandwidth brought me here. I'd love to just clone again, but it was painful enough the first time, so I'm one of those looking for a quicker solution. – Sz. Jul 11 '19 at 17:46
  • 1
    worked for me when source branch contained updates like file renames from "general" to "General". On Windows it doesn't matter what the case is, so this approach unblocked me. – Someone Somewhere Aug 08 '19 at 19:20
  • Mecurial has `hg update` yet there is no equivalent in git... – Jack Mar 11 '20 at 15:42
  • It would be more consistent if you could do `git pull --force` and it would just overwrite your local branch. Seeing as you can do the opposite, overwriting the remote by `git push --force` – Jonny Mar 12 '20 at 03:34
  • 1
    Note that the master branch is now called main branch by default so pay attention copy-pasters, as these command may not work any more. – Matt Oct 27 '20 at 13:21
  • 1
    If you run git checkout -b backup-master, you should go back to your branch (master in the example) before running the git reset. Otherwise, you can use git branch backup-master instead to create the backup branch but stay in master. – Karim Sonbol Dec 11 '20 at 12:19
  • After doing this I've got a "fatal: Couldn't find remote ref master" when I do git pull origin master – G M Apr 14 '21 at 06:22
  • I am consent with the first part, but instead of git reset --hard origin/master, also a git checkout --force should do the job. – schnedan Nov 10 '21 at 18:03
  • if you want to use it inside of a script see my answer: https://stackoverflow.com/questions/1125968/how-do-i-force-git-pull-to-overwrite-local-files/50522849#50522849 – warch Dec 16 '21 at 10:31
  • Even though this is the accepted answer, it technically doesn't solve OP's original problem, which had to do with overwriting untracked files (which are left untouched by this answer). – ryanwebjackson Mar 10 '22 at 03:19
  • Use main instead of master due to recent naming changes. – Jan Pansky Nov 23 '22 at 09:40
  • maybe someone should use `origin/main` instead of `origin/master` – plhn Feb 03 '23 at 05:57
  • instead of `git reset --hard origin/my-branch`, you could do a `git reset --mixed origin/my-branch` if you want to keep your unstaged modifications locally. – OroshiX Feb 07 '23 at 11:48
1336

This will remove all uncommitted changes, even if staged,
and then pull:

git reset --hard HEAD
git pull

But any local file that's not tracked by Git will not be affected.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
Travis Reeder
  • 38,611
  • 12
  • 87
  • 87
  • 33
    I've done this and some local files that were no longer in repo were left on the disk. – Piotr Owsiak Apr 08 '11 at 16:00
  • 41
    I do not think that this is correct. the above will perform a merge, not overwrite which was requested in the question: "How to force git to overwrite them?" I do not have the answer, I am currently looking for it.. at the moment I switch to the branch with with the code that I want to keep "git checkout BranchWithCodeToKeep", then do "git branch -D BranchToOverwrite" and then finally "git checkout -b BranchToOverwrite". you will now have the exact code from BranchWithCodeToKeep on the branch BranchToOverwrite without having to perform a merge. – felbus Jul 13 '11 at 10:11
  • 305
    instead of merging using 'git pull', try git fetch --all followed by 'git reset --hard origin/master' – Lloyd Moore Feb 21 '12 at 14:56
  • Lloyd Moore's suggestion is correct, but beware that it can remove local unpushed commits from your branch. – Matthijs P May 17 '12 at 08:23
  • 9
    yep, the @lloydmoore solution worked for me. Could do with being an answer rather than just a comment. – Max Williams Nov 19 '12 at 09:54
  • 5
    This will reset the current changes back to the last branch commit pulled. Then git pull merges the changes from the latest branch. This did exactly what I wanted it to do.. Thanks! – Codeversed Dec 05 '14 at 17:42
  • 2
    Good answer, but please add more detail, I mean some people may don't know anything about the reset and lose their files... – Mohammad Kermani Jan 17 '17 at 12:54
  • `git reset --hard HEAD` doesn't really reset all in some cases – Finesse Mar 06 '18 at 02:19
  • This is mostly what I think of when I think of forcing the pull. Mostly after I tried some settings – Mia loha.dev Jul 04 '18 at 09:17
  • if you want to use it inside of a script see my answer: https://stackoverflow.com/questions/1125968/how-do-i-force-git-pull-to-overwrite-local-files/50522849#50522849 – warch Dec 16 '21 at 10:32
  • There should be a comment about untracked file (those that were not stashed by my latest "git stash"), I want to be sure that I keep those so I don't dare to use this solution – moodymudskipper Nov 04 '22 at 17:14
  • `git pull` throws your terminal into VIM. I can never remember how to get out of VIM. – Thomas David Kehoe Mar 08 '23 at 17:15
  • I like this approach the best. Add to it `git clean -fdx` and you are gold. – DrBeco Apr 03 '23 at 01:59
  • that doesn't work if local master and remote master have diverged, what was in my case. – Alex May 05 '23 at 12:21
  • This also removes changes for files that were not modified on remote branch! – Viktor Mukhachev Jun 27 '23 at 11:01
588

WARNING: git clean deletes all your untracked files/directories and can't be undone.


Sometimes just clean -f does not help. In case you have untracked DIRECTORIES, -d option also needed:

# WARNING: this can't be undone!

git reset --hard HEAD
git clean -f -d
git pull

WARNING: git clean deletes all your untracked files/directories and can't be undone.

Consider using -n (--dry-run) flag first. This will show you what will be deleted without actually deleting anything:

git clean -n -f -d

Example output:

Would remove untracked-file-1.txt
Would remove untracked-file-2.txt
Would remove untracked/folder
...
David Avsajanishvili
  • 7,678
  • 2
  • 22
  • 24
  • 1
    You can give git clean a path argument to be more specific and avoid deleting untracked files that aren't conflicting. – joachim Oct 18 '11 at 10:08
  • 7
    I think the scenario description makes it clear that he doesn't really want to throw away the content. Rather what he wants is to stop git baulking at overwriting the files. @Lauri, this should not have happened to you. Unfortunately people seem to have misread the essence of scenario description - see my suggestion. – Hedgehog Feb 11 '12 at 23:05
  • 25
    **FINALLY**. git clean -f -d is handy when make clean fails to clean everything. – earthmeLon Jun 23 '12 at 04:32
  • If you want to sync the whole directory with the remote repo, this is the way to go. – Johannes Ewald Feb 11 '13 at 12:04
  • 8
    @crizCraig unless they are added in `.gitignore` – Bleeding Fingers Jun 13 '13 at 06:58
  • @BleedingFingers Then add `-x`. But existing files that are covered by `.gitignore` shouldn't be a problem: assuming the other contributors to that repo use the same `.gitignore` file, a pull won't receive any commits that add conflicting files. –  Jun 07 '15 at 00:18
  • 9
    @earthmeLon, for that you might want `git clean -dfx`. The `-x` ignores .gitignore. Typically your build products will be in .gitignore. – Paul Draper Aug 12 '15 at 18:28
  • 1
    It can be good to run `git clean -nfd` first, which only shows, *what would be removed* before it's actually done, that is before you run into troubles. :-) – Velda Aug 16 '18 at 14:26
  • That --dry-run tip is safe +1 – P.M Jul 22 '22 at 18:08
485

Like Hedgehog I think the answers are terrible. But though Hedgehog's answer might be better, I don't think it is as elegant as it could be. The way I found to do this is by using fetch and merge with a defined strategy. Which should make it so that your local changes are preserved as long as they are not one of the files that you are trying to force an overwrite with.

First do a commit of your changes

 git add *
 git commit -a -m "local file server commit message"

Then fetch the changes and overwrite if there is a conflict

 git fetch origin master
 git merge -s recursive -X theirs origin/master

-X is an option name, and theirs is the value for that option. You're choosing to use their changes (the other option is ours changes) if there is a conflict.

TheTechRobo the Nerd
  • 1,249
  • 15
  • 28
Richard
  • 5,584
  • 1
  • 19
  • 22
  • 75
    This is the best answer I've seen so far. I haven't tried it, but unlike other answers, this doesn't attempt to nuke all your untracked files, which is very dangerous for obvious reasons. – huyz May 07 '12 at 09:36
  • 8
    Ditto - this worked for me when doing a very large merge (GitHub pull request) where I just wanted to accept it all on top of what I had. Good answer! In my case the last two commands were: 1) `get fetch other-repo`; 2) `git merge -s recursive -X theirs other-repo/master` – quux00 Jul 27 '12 at 01:44
  • 4
    This will overwrite any conflicts with the repositories files and not your local ones, correct? – Nathan F. Dec 05 '14 at 11:40
  • 6
    Best answer. The highest accepted answer left me in my case on detached head. I switched back to local master branch and ran `git merge -X theirs origin/master` – petergus Mar 11 '16 at 12:46
  • 1
    Tried this - then add/commit my new changed files, but still said my branch was behind remote when I tried to push. Massive wasted time because "git pull" doesn't ask "Overwrite local? y/n/all". – JosephK Jul 26 '16 at 03:57
  • 1
    Hang on...doesn't have `git add *` and `git commit -a ` have the same effect? Why would you need both? – Marcel Stör Apr 25 '17 at 20:41
  • 1
    @MarcelStör you don't need both but they also don't do the same thing. `git commit -a` only has that affect on files that are already tracked; `git add *` will add files that are not tracked. So if you do `git commit -a` it won't catch new files, then you might need to do a `git add` afterward, but it you do `git add *` you won't need `-a` on the commit. – briantist Apr 04 '18 at 20:47
  • 2
    The problem with this (excellent) answer, is it adds the all the local files, which sometimes may not be what you want. You may just want to add the specific files that were omitted. But the best thing about it is, it gets him to do what he should have done -- add them locally. You probably won't need the -X theirs strategy, since they're the same image. In fact, I'd suggest leaving it off at first, just to find out if there are any anomalies, and add it in if there are, after reviewing that 'theirs' is always the correct choice. But then, I'm paranoid. – Bob Kerns Jun 28 '18 at 20:27
  • 10
    i just wanted freaking git to overwrite everything and shut up about it. after all im just using it between my work pc and some raspberry pi systems. Whishing for a force overwrite option, at least for project leader – clockw0rk Jun 05 '19 at 14:39
  • after trying this command I still get the same error " untracked working tree files would be overwritten by merge " and a long yet incomplete list of the files I can't simply force it to overwrite. – Patrick Parker Oct 02 '20 at 15:48
  • hmmm... maybe try ```git add .``` first – Richard Oct 05 '20 at 13:17
  • 1
    If you don't want a merge commit you can run `git pull --rebase=interactive -s recursive -X theirs` instead and drop your local undesired changes [as detailed in this answer](https://stackoverflow.com/a/68732289/2166823) – joelostblom Aug 10 '21 at 19:05
  • @clockw0rk While any good VCS would not overwrite local changes without a user requests it, consider using mercurial. Git has some bad design ideas, which caused git now has some defaults deactivating some of the "D" in DVCS. Mercurial don't suffer this problems. Pushing from any A to any B where B is not a central Server Repro is now disabled by default in git, but works in mercurial... If you did wrong, nothing is lost, just a double head which you can rebase or merge... – schnedan Nov 10 '21 at 18:08
416

Instead of doing:

git fetch --all
git reset --hard origin/master

I'd advise doing the following:

git fetch origin master
git reset --hard origin/master

No need to fetch all remotes and branches if you're going to reset to the origin/master branch right?

Johanneke
  • 5,443
  • 4
  • 20
  • 33
  • 3
    Your answer is just what you needed for your rep. I must ask, does this also remove all untracked files? – Nicolas De Jay Jan 07 '14 at 06:38
  • 6
    Yeah, most of my rep is coming from here :) This will also remove all untracked files. Something I had forgotten and was painfully reminded of just 2 days ago... – Johanneke Jan 09 '14 at 12:01
  • 1
    See the comments on this other answer: http://stackoverflow.com/a/8888015/2151700 – Johanneke Jan 09 '14 at 12:02
  • This did not remove my untracked files; which is actually what I'd expect. Is there a reason it might for some people and not for others? – Ada Richards Apr 19 '16 at 15:27
  • Untracked files are not affect4ed by git reset. If you want them to be removed as well, do `git add .` first, before `git reset --hard` – Johanneke Aug 15 '17 at 09:12
  • 1
    This is exactly what I needed: something that overwrites untracked files that exist in the remote, and leaves everything else intact. – Ledazinha Dec 20 '17 at 22:37
  • "master" is no longer politically correct, git now prefers "main". – Rick Graves Jun 25 '21 at 22:19
  • This seems much simpler (and even better?) than the most upvoted answers, so I wonder why there's such a big gap in the voting? I've upvoted this one for now, although I don't really know what's going on! I started a [Git chat room on StackOverflow](https://chat.stackoverflow.com/rooms/228186/git) in case anyone has an answer to my question which would go beyond what can fit in a comment. – Nike Jul 18 '22 at 19:18
  • Well, `git fetch origin master` results in `fatal: Couldn't find remote ref master` for me, which maybe answers the question from my last comment! – Nike Jul 18 '22 at 19:30
158

It looks like the best way is to first do:

git clean

To delete all untracked files and then continue with the usual git pull...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jakub Troszok
  • 99,267
  • 11
  • 41
  • 53
  • 4
    I tried using "git clean" to solve the same issue, but it did not resolve it. git status says "Your branch and 'origin/master' have diverged, # and have 2 and 9 different commit(s) each, respectively." and git pull says something similar to what you have above. – slacy Sep 24 '09 at 04:25
  • would he not need to change to the master branch and then do git clean for it to work? Then he can flip back to whatever development branch he was working from. – suitedupgeek Jan 25 '10 at 21:38
  • @slacy: Then you need to merge the two branches. – Xiong Chiamiov Feb 05 '10 at 00:07
  • 48
    git clean is a rather blunt instrument, and could throw away a lot of things that you may want to keep. Better to remove or rename the files that git is complaining about until the pull succeeds. – Neil Mayhew Jul 02 '10 at 13:21
  • 2
    I do not think this works in general. Isn't there a way to do basically a git clone remote via a forced git pull? – mathtick Nov 29 '10 at 18:30
  • 19
    @mathick: `git fetch origin && git reset --hard origin/master` – Arrowmaster Feb 23 '11 at 04:24
  • I needed to add a `-x` to that `git clean` to get it to work for me, for some reason (`-d` wasn't deleting a `.ideas` directory for some reason), but this fixed my problem, certainly. – Owen Blacker Dec 19 '11 at 12:29
  • avoid sudden cardiac arrest: use `git clean -n` first – doub1ejack Jul 30 '13 at 14:19
  • 3
    Is `git clean` the best answer here? Seems like removing files isn't necessarily what the OP wants. They asked for 'an overwrite of local files' not deletion. – JohnAllen Mar 04 '14 at 08:28
  • 1
    `git clean` by itself doesn't seem to help, @Arrowmaster 's solution is closer, but a better one by Lloyd Moore is in the next answer. – Neil Monroe Jun 10 '15 at 21:12
  • 1
    Don't ever do anything 'git' (or even have a .git folder) except in a copy of your actual work folder, and avoid all cardiac stress. Don't give git and its obtuse syntax/methods the opportunity to wreck you in the first place. – JosephK Jul 26 '16 at 04:12
133

Warning, doing this will permanently delete your files if you have any directory/* entries in your gitignore file.

Some answers seem to be terrible. Terrible in the sense of what happened to @Lauri by following David Avsajanishvili suggestion.

Rather (git > v1.7.6):

git stash --include-untracked
git pull

Later you can clean the stash history.

Manually, one-by-one:

$ git stash list
stash@{0}: WIP on <branch>: ...
stash@{1}: WIP on <branch>: ...

$ git stash drop stash@{0}
$ git stash drop stash@{1}

Brutally, all-at-once:

$ git stash clear

Of course if you want to go back to what you stashed:

$ git stash list
...
$ git stash apply stash@{5}
Hedgehog
  • 5,487
  • 4
  • 36
  • 43
  • Aren't you assuming that a commit has never been performed? In my case I made several commits to my local branch, but wanted to "reset" everything back to the remote branch – Lee Francis Mar 20 '12 at 10:55
  • 2
    No I don't think so. Stashing just moves uncommitted files out of the way. The above also moves (stashes) files that git does not track. This prevents files that have been added to the remote, which have not yet pulled down to your machine - but which you have created (!) - to be pulled down. All without destroying the uncommitted work. Hope that makes sense? – Hedgehog Mar 20 '12 at 23:54
  • 3
    If you don't have 1.7.6, you can mimic `--include-untracked` simply by temporarily `git add`-ing your entire repo, then immediately stashing it. – nategood May 01 '12 at 22:48
  • 3
    I agree with Hedgehog. If you do the popular answers here, you are more than likely going to find you've inadvertently killed a lot of stuff that you didn't really want to lose. – AfroRick Jan 31 '13 at 21:28
  • 1
    I had other untracked files--besides the one the merge/pull wanted to overwrite, so this solution worked best. `git stash apply` brought back all my untracked files with the exception (rightly) of the ones that the merge had already created: "already exists, no checkout." Worked perfectly. – BigBlueHat Apr 25 '13 at 04:55
  • 1
    This can be the easiest way to hose a repo unintentionally, just like what happened to @Lauri, but worse because you think you're protecting files from deletion. If you have one `.gitignore` rule that has a wildcard in it, kiss them goodbye. [Explanation.](http://blog.icefusion.co.uk/git-stash-can-delete-ignored-files-git-stash-u/) – Walf Nov 30 '16 at 07:05
  • 2
    This is the cleanest answer, and should be the accepted one. To save some typing you can use the short form: `git stash -u`. – ccpizza Mar 23 '17 at 08:30
  • The link about git stash --include-untracked destroying folders that are gitignored is dead - let's find a replacement. In the meantime, the @Waif comment about **how this answer can destroy gitignore'd folders** should be upvoted, and preferably converted into a new answer. The [GitLab issue](http://blog.icefusion.co.uk/git-stash-can-delete-ignored-files-git-stash-u/) you linked has details. I use `git stash` a lot and was very surprised to hear it can destroy files. – RichVel Apr 15 '19 at 20:09
114

You might find this command helpful to throw away local changes:

git checkout <your-branch> -f

And then do a cleanup (removes untracked files from the working tree):

git clean -f

If you want to remove untracked directories in addition to untracked files:

git clean -fd
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vishal
  • 19,879
  • 23
  • 80
  • 93
  • I think the scenario description makes it clear that he doesn't really want to throw away the content. Rather what he wants is to stop git baulking at overwriting the files. See my suggestion. – Hedgehog Feb 11 '12 at 23:03
  • 4
    Though that answer might not fit exactly the description, it still saved me from the frustration of git twiddling with the carriage returns (event with autocrlf false). When git reset --hard HEAD does not leave you with "no" modified files, these "-f" flags are quite helpful. Thanks a bunch. – Kellindil Jan 16 '13 at 10:28
  • "git clean -fd" saved me – Jzapata Oct 12 '22 at 19:13
103

Instead of merging with git pull, try this:

git fetch --all

followed by:

git reset --hard origin/master.

sbarb
  • 95
  • 1
  • 2
  • 9
Lloyd Moore
  • 3,117
  • 1
  • 32
  • 32
  • this wont work in scripts cause you have to know the branch name. Look at my solution for a generic way – warch Nov 25 '21 at 09:02
76

The only thing that worked for me was:

git reset --hard HEAD~5

This will take you back five commits and then with

git pull

I found that by looking up how to undo a Git merge.

Community
  • 1
  • 1
Chris BIllante
  • 801
  • 6
  • 3
  • This was what ultimately worked for me as I had force pushed my branch to the origin repo and kept getting merge conflicts when trying to pull it to my remote repo.. – jwfrench May 07 '14 at 05:16
  • Hi, actually this is a trick for a `work around` but really effective. Because some conflicts may happen just in few commits then reverting 5 commits will make sure no conflicts with remote code. – Hoang Le Nov 21 '14 at 10:03
68

The problem with all these solutions is that they are all either too complex or, an even bigger problem, is that they remove all untracked files from the webserver, which we don't want since there are always needed configuration files which are on the server and not in the Git repository.

Here is the cleanest solution which we are using:

# Fetch the newest code
git fetch

# Delete all files which are being added, so there
# are no conflicts with untracked files
for file in `git diff HEAD..origin/master --name-status | awk '/^A/ {print $2}'`
do
    rm -f -- "$file"
done

# Checkout all files which were locally modified
for file in `git diff --name-status | awk '/^[CDMRTUX]/ {print $2}'`
do
    git checkout -- "$file"
done

# Finally pull all the changes
# (you could merge as well e.g. 'merge origin/master')
git pull
  • The first command fetches the newest data.

  • The second command checks if there are any files that are being added to the repository and deletes those untracked files from the local repository which would cause conflicts.

  • The third command checks-out all the files which were locally modified.

  • Finally, we do a pull to update to the newest version, but this time without any conflicts, since untracked files which are in the repo don't exist anymore and all the locally modified files are already the same as in the repository.

Vlad L.
  • 154
  • 1
  • 9
Strahinja Kustudic
  • 4,175
  • 1
  • 24
  • 18
  • Using "git merge origin/master" as the last line (like you say in your note) instead of "git pull" will be faster as you've already pulled down any changes from the git repo. – Josh May 06 '13 at 06:21
  • 1
    Yeah of course, `git merge origin/master` will be faster and probably even safer. Since if someone pushed new changes during the removal of of files of this script (which is not likely to happen, but possible), the whole pull could fail. The only reason I put `pull` in there is because someone might not be working on the master branch, but some other branch and I wanted the script to be universal. – Strahinja Kustudic Sep 01 '13 at 22:25
  • If you have locally created files like option files, put them in `.gitignore`. – Sebi Nov 21 '17 at 11:41
65

First of all, try the standard way:

git reset HEAD --hard # To remove all not committed changes!
git clean -fd         # To remove all untracked (non-git) files and folders!

Warning: Above commands can results in data/files loss only if you don't have them committed! If you're not sure, make the backup first of your whole repository folder.

Then pull it again.

If above won't help and you don't care about your untracked files/directories (make the backup first just in case), try the following simple steps:

cd your_git_repo  # where 'your_git_repo' is your git repository folder
rm -rfv *         # WARNING: only run inside your git repository!
git pull          # pull the sources again

This will REMOVE all git files (excempt .git/ dir, where you have all commits) and pull it again.


Why git reset HEAD --hard could fail in some cases?

  1. Custom rules in .gitattributes file

    Having eol=lf rule in .gitattributes could cause git to modify some file changes by converting CRLF line-endings into LF in some text files.

    If that's the case, you've to commit these CRLF/LF changes (by reviewing them in git status), or try: git config core.autcrlf false to temporary ignore them.

  2. File system incompability

    When you're using file-system which doesn't support permission attributes. In example you have two repositories, one on Linux/Mac (ext3/hfs+) and another one on FAT32/NTFS based file-system.

    As you notice, there are two different kind of file systems, so the one which doesn't support Unix permissions basically can't reset file permissions on system which doesn't support that kind of permissions, so no matter how --hard you try, git always detect some "changes".

kenorb
  • 155,785
  • 88
  • 678
  • 743
62

Bonus:

In speaking of pull/fetch/merge in the previous answers, I would like to share an interesting and productive trick,

git pull --rebase

This above command is the most useful command in my Git life which saved a lot of time.

Before pushing your newly commit to server, try this command and it will automatically synchronise the latest server changes (with a fetch + merge) and will place your commit at the top in the Git log. There isn't any need to worry about manual pull/merge.

Find details in What does "git pull --rebase" do?.

Community
  • 1
  • 1
Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
59

I had the same problem. No one gave me this solution, but it worked for me.

I solved it by:

  1. Delete all the files. Leave just the .git directory.
  2. git reset --hard HEAD
  3. git pull
  4. git push

Now it works.

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
John John Pichler
  • 4,427
  • 8
  • 43
  • 72
  • 1
    Same here. Sometimes only the very hard solution works, it happens often that only reset and clean are not enough somehow... – jdehaan Dec 15 '11 at 11:28
49

Here is a generic solution if you do not always want to paste the branch name or you want to automate this within a script

git fetch
git reset --keep origin/$(git rev-parse --abbrev-ref HEAD)

If you want to reset your local changes too:

git fetch
git reset --hard origin/$(git rev-parse --abbrev-ref HEAD)

You also could add a bash alias using this command:

alias gplf='git fetch && echo "HEAD was at $(git rev-parse --short HEAD)" && git reset --hard origin/$(git rev-parse --abbrev-ref HEAD)'
warch
  • 2,387
  • 2
  • 26
  • 43
  • 2
    If you find yourself using this frequently add a bash shortcut `alias gplf='git fetch && echo "HEAD was at $(git rev-parse --short HEAD)" && git reset --hard origin/$(git rev-parse --abbrev-ref HEAD)'` – Paul Odeon Nov 13 '19 at 09:43
  • 1
    Brilliant. Thanks! People do not consider automated scripts when answering. This is very elegant when you just can't pass the branch name along. – Zeno Popovici Sep 24 '20 at 16:24
  • 2
    This middle one worked for me: `git fetch` followed by `git reset --hard origin/$(git rev-parse --abbrev-ref HEAD)`. I chose it for its simplicity and the recentness of the answer. – Nike Jul 18 '22 at 19:33
38

I had a similar problem. I had to do this:

git reset --hard HEAD
git clean -f
git pull
Alexsander Akers
  • 15,967
  • 12
  • 58
  • 83
Ryan
  • 429
  • 4
  • 2
35

I summarized other answers. You can execute git pull without errors:

git fetch --all
git reset --hard origin/master
git reset --hard HEAD
git clean -f -d
git pull

Warning: This script is very powerful, so you could lose your changes.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Robert Moon
  • 1,025
  • 10
  • 17
  • 2
    This will overwrite modified files (files that were previously checked in) and it will remove untracked files (files that have never been checked in). Exactly what I was looking for, thanks! – styfle Mar 03 '16 at 16:01
  • 3
    I suspect the third line `git reset --hard HEAD` may be redundant; my local man page (2.6.3) say that `reset` in the second line `git reset --hard origin/master` _"defaults to HEAD in all forms."_ – Ada Richards Apr 19 '16 at 15:40
  • 2
    @arichards I think your suspect is right but if second line will not work(by any reason) third line work well to reset. This solution doesn't need to be optimized. I just summarized other answers. That's all. Thank you for your comment. :) – Robert Moon Apr 20 '16 at 02:12
  • Thanks for the summary. These steps are indeed powerful :) – Glorian Dec 10 '20 at 17:28
29

Based on my own similar experiences, the solution offered by Strahinja Kustudic above is by far the best. As others have pointed out, simply doing hard reset will remove all the untracked files which could include lots of things that you don't want removed, such as config files. What is safer, is to remove only the files that are about to be added, and for that matter, you'd likely also want to checkout any locally-modified files that are about to be updated.

That in mind, I updated Kustudic's script to do just that. I also fixed a typo (a missing ' in the original).

#/bin/sh

# Fetch the newest code
git fetch

# Delete all files which are being added,
# so there are no conflicts with untracked files
for file in `git diff HEAD..origin/master --name-status | awk '/^A/ {print $2}'`
do
    echo "Deleting untracked file $file..."
    rm -vf "$file"
done

# Checkout all files which have been locally modified
for file in `git diff HEAD..origin/master --name-status | awk '/^M/ {print $2}'`
do
    echo "Checking out modified file $file..."
    git checkout $file
done

# Finally merge all the changes (you could use merge here as well)
git pull
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Rolf Kaiser
  • 551
  • 6
  • 9
  • Using "git merge origin/master" as the last line (like you say in your note) instead of "git pull" will be faster as you've already pulled down any changes from the git repo. – Josh May 06 '13 at 06:20
  • The checkout of modified files is needed, so this works 100% of times. I updated my script with that a long time ago, but forgot to update here as well. I also use it a little differently than you. I checkout files which have any type of modification, not just M, so it works all the time. – Strahinja Kustudic Sep 01 '13 at 22:48
25

It seems like most answers here are focused on the master branch; however, there are times when I'm working on the same feature branch in two different places and I want a rebase in one to be reflected in the other without a lot of jumping through hoops.

Based on a combination of RNA's answer and torek's answer to a similar question, I've come up with this which works splendidly:

git fetch
git reset --hard @{u}

Run this from a branch and it'll only reset your local branch to the upstream version.

This can be nicely put into a git alias (git forcepull) as well:

git config alias.forcepull "!git fetch ; git reset --hard @{u}"

Or, in your .gitconfig file:

[alias]
  forcepull = "!git fetch ; git reset --hard @{u}"

Enjoy!

Community
  • 1
  • 1
JacobEvelyn
  • 3,901
  • 1
  • 40
  • 51
24

I had the same problem and for some reason, even a git clean -f -d would not do it. Here is why: For some reason, if your file is ignored by Git (via a .gitignore entry, I assume), it still bothers about overwriting this with a later pull, but a clean will not remove it, unless you add -x.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tierlieb
  • 287
  • 3
  • 4
23

I am not sure why anyone did not talk about FETCH_HEAD yet.

git fetch origin master && git reset --hard FETCH_HEAD

If you want to put it in an alias, the command would be:

git config --global alias.fpull '!git fetch origin master && git reset --hard FETCH_HEAD'
Ahmad Ismail
  • 11,636
  • 6
  • 52
  • 87
23

I believe there are two possible causes of conflict, which must be solved separately, and as far as I can tell none of the above answers deals with both:

  • Local files that are untracked need to be deleted, either manually (safer) or as suggested in other answers, by git clean -f -d

  • Local commits that are not on the remote branch need to be deleted as well. IMO the easiest way to achieve this is with: git reset --hard origin/master (replace 'master' by whatever branch you are working on, and run a git fetch origin first)

tiho
  • 6,655
  • 3
  • 31
  • 31
22

An easier way would be to:

git checkout --theirs /path/to/file.extension
git pull origin master

This will override your local file with the file on git

maximus 69
  • 1,388
  • 4
  • 22
  • 35
20

I know of a much easier and less painful method:

$ git branch -m [branch_to_force_pull] tmp
$ git fetch
$ git checkout [branch_to_force_pull]
$ git branch -D tmp

That's it!

Ricky McMaster
  • 4,289
  • 2
  • 24
  • 23
ddmytrenko
  • 796
  • 7
  • 16
  • I tried doing as suggested in this answer. NO FILES AT ALL were pulled down from the remote repository. Actually not very surprising when you think about it - after all there is no reference at all to `origin/`. – Henke Dec 10 '20 at 11:58
  • Hmm this looks like what I need to try. I have 50+ files & untracked files in my working copy with my personal debug code. So every time I have merge conflicts on a handful of files, it is unwieldy to do any of the other methods (like reset, stash, etc.) mentioned in this thread. – Keith Knauber Mar 08 '23 at 18:58
20

I have a strange situation that neither git clean or git reset works. I have to remove the conflicting file from git index by using the following script on every untracked file:

git rm [file]

Then I am able to pull just fine.

Jacob Gunther
  • 351
  • 5
  • 14
Chen Zhang
  • 227
  • 2
  • 3
  • Thanks! I found that this is needed if you've made any special adjustments to ignore changes on file in the repo. i.e `git update-index --assume-unchanged ` – skupjoe Jan 20 '23 at 23:25
19

I just solved this myself by:

git checkout -b tmp # "tmp" or pick a better name for your local changes branch
git add -A
git commit -m 'tmp'
git pull
git checkout master # Or whatever branch you were on originally
git pull
git diff tmp

where the last command gives a list of what your local changes were. Keep modifying the "tmp" branch until it is acceptable and then merge back onto master with:

git checkout master && git merge tmp

For next time, you can probably handle this in a cleaner way by looking up "git stash branch" though stash is likely to cause you trouble on the first few tries, so do first experiment on a non-critical project...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Simon B.
  • 2,530
  • 24
  • 30
17

Just do

git fetch origin branchname
git checkout -f origin/branchname // This will overwrite ONLY new included files
git checkout branchname
git merge origin/branchname

So you avoid all unwanted side effects, like deleting files or directories you wanted to keep, etc.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2696128
  • 191
  • 1
  • 2
  • Nice. By first using `checkout -f` into the branch I wanted to merge from, that got rid of all the problematic untracked files. Then I could checkout again my destination, and finally merge without issues. – Patrick Parker Oct 02 '20 at 17:06
16

Requirements:

  1. Track local changes so no-one here ever loses them.
  2. Make the local repository match the remote origin repository.

Solution:

  1. Stash the local changes.
  2. Fetch with a clean of files and directories ignoring .gitignore and hard reset to origin.

    git stash --include-untracked
    git fetch --all
    git clean -fdx
    git reset --hard origin/master
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vezenkov
  • 4,009
  • 1
  • 26
  • 27
15

Reset the index and the head to origin/master, but do not reset the working tree:

git reset origin/master
  • I personally found this to be most useful. It then keeps your working tree so you can check it in again. For my issue, I had the same files deleted as being added so it was stuck. Weird, I know. – King Friday Jan 04 '14 at 21:03
15

These four commands work for me.

git reset --hard HEAD
git checkout origin/master
git branch -D master
git checkout -b master

To check/pull after executing these commands

git pull origin master

I tried a lot but finally got success with these commands.

Vishesh Chandra
  • 6,951
  • 6
  • 35
  • 38
  • 2
    "git branch -D master" delete the branch. so be careful with it. I prefer to use "git checkout origin/master -b " which create a new branch with a new name and you done need 3,4 lines. Also recommended to use "git clean -f" as well. – Chand Priyankara Apr 05 '14 at 11:49
15

Despite the original question, the top answers can cause problems for people who have a similar problem, but don't want to lose their local files. For example, see Al-Punk and crizCraig's comments.

The following version commits your local changes to a temporary branch (tmp), checks out the original branch (which I'm assuming is master) and merges the updates. You could do this with stash, but I've found it's usually easier to simply use the branch / merge approach.

git checkout -b tmp
git add *; git commit -am "my temporary files"
git checkout master

git fetch origin master
git merge -s recursive -X theirs origin master

where we assume the other repository is origin master.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Snowcrash
  • 80,579
  • 89
  • 266
  • 376
13

I read through all the answers but I was looking for a single command to do this. Here is what I did. Added a git alias to .gitconfig

[alias]
      fp = "!f(){ git fetch ${1} ${2} && git reset --hard ${1}/${2};};f"

Run your command as

git fp origin master

equivalent to

git fetch origin master
git reset --hard origin/master
Venkat Kotra
  • 10,413
  • 3
  • 49
  • 53
10

Don't use git reset --hard. That will wipe their changes which may well be completely undesirable. Instead:

git pull
git reset origin/master
git checkout <file1> <file2> ...

You can of course use git fetch instead of git pull since it clearly isn't going to merge, but if you usually pull it makes sense to continue to pull here.

So what happens here is that git pull updates your origin/master reference; git reset updates your local branch reference on to be the same as origin/master without updating any files, so your checked-out state is unchanged; then git checkout reverts files to your local branch index state as needed. In cases where exactly the same file has been added on live and on upstream master, the index already matches the file following the reset, so in the common case you don't need to do git checkout at all.

If the upstream branch also contains commits which you want to apply automatically, you can follow a subtle variation on the process:

git pull
git merge <commit before problem commit>
git reset <problem commit>
git checkout <file1> <file2> ...
git pull
Jim Driscoll
  • 894
  • 11
  • 8
8

This is the best practice for reverting changes:

  • git commit Commit your staged changes so they will be saved in the reflog ( see below )
  • git fetch Fetch the latest upstream changes
  • git reset --hard origin/master Hard reset to the origin master branch

The reflog records branches and other references being updated in the local repository. Or simply put - the reflog is the history of your changes.

So it's always a great practice to commit. Commits are appended to the reflog which ensures you will always have a way to retrieve the deleted code.

Jordan Parker
  • 239
  • 3
  • 8
8
git fetch --all
git reset --hard origin/develop
Achraf Farouky
  • 813
  • 10
  • 11
6

On Windows, do this single command:

git fetch --all & git reset --hard origin/master
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Luca C.
  • 11,714
  • 1
  • 86
  • 77
  • Why would it be different than on, e.g., Linux? Which particular implementation/package of git do you use? And/or which environment (e.g. MinGW)? – Peter Mortensen Apr 27 '18 at 12:57
  • I am not sure, only sure that works in windows. In linux what is the separator to concatenate two commands in a single line? (not the pipe, somply concatenate without passing the outoput) – Luca C. Apr 29 '18 at 08:53
5

I used this command to get rid of the local files preventing me from doing a pull/merge. But be careful! Run git merge … first to see whether there are only those files you really want to remove.

git merge origin/master 2>&1 >/dev/null | grep ^[[:space:]] | sed s/^[[:space:]]//g | xargs -L1 rm
  • git merge lists among other things all those files. They are prepended by some white-space.
  • 2>&1 >/dev/null redirects the error output to the standard one so it is picked up by grep.
  • grep ^[[:space:]] filters only the lines with file names.
  • sed s/^[[:space:]]//g trims the white-space from the beginning.
  • xargs -L1 rm calls rm on each of those files, deleting them.

Handle with care: Whatever git merge outputs, the rm will be called for every line beginning with a white-space.

Glutexo
  • 547
  • 6
  • 13
5

I was trying to use the Material2 branch on the Angular2-Webpack-Starter and had a heck of a time. This was the only way I could download and use that branch.

git clone --depth 1 https://github.com/angularclass/angular2-webpack-starter.git

cd angular2-webpack-starter/

git checkout -b material2

Open the project folder and delete all non-hidden files and folders. Leave all the hidden ones.

git add .

git commit -m "pokemon go"

git reset --hard

git pull origin material2

(When the editor pops up, hit ':wq', and then press Enter)

Now you are ready.

MarkHu
  • 1,694
  • 16
  • 29
Post Impatica
  • 14,999
  • 9
  • 67
  • 78
5

If you are working on your code and find the new changes a huge mistake or unwanted you can simply use an alternative like:

git restore .

where . means all the files present in the directory.

4

You could ignore that file with a file in your project base folder:

.gitignore

public/images/*

Then pull the changes and then remove that line from your gitignore file.

DanielG
  • 216
  • 2
  • 5
4

Another way of solving this is to first stash any uncommitted changes using git stash and then run

git pull --rebase=interactive -s recursive -X theirs

In the interactive rebase you can change all your local undesired commits to drop, which will get rid of them and leave you at the head of the remote branch without introducing a merge commit.

Now you can run git stash apply if you had local stashed changed that you want to bring back.

joelostblom
  • 43,590
  • 17
  • 150
  • 159
4

"My local changes was small, or my changes doesn't work. I just want to reset everything back to original. I know that all my local changes will be lost."

If that's the case then:

git reset --hard
git pull
Arief Karfianto
  • 235
  • 2
  • 8
4

This solution is always running.

cd $GIT_ROOT_DIRECTORY
git fetch origin/$TARGET_BRANCH
git rm -rf --cached .
git reset --hard origin/TARGET_BRANCH
git clean -df
git pull origin $TARGET_BRANCH
kkhhww
  • 51
  • 4
4

The key to this is using FETCH_HEAD.

git fetch origin <your e.g. feature branch>
git reset --hard FETCH_HEAD

I've tried HEAD and git pull and none worked.

Michael Brenndoerfer
  • 3,483
  • 2
  • 39
  • 50
3

1: Reset to a previous commit

git reset --hard HEAD

2: Delete Untracked Files

git clean -f

3: Pull the commits

git pull

Sources:

abhijithvijayan
  • 835
  • 12
  • 17
2

Despite the fact that this question has already many answers, the original question is to solve this question

error: Untracked working tree file 'public/images/icon.gif' would be overwritten by merge

As binary files can't be merged a simple answer is

git checkout public/images/icon.gif

With that the file will recover the previous state it had in this branch.

I usually do git stash if I don't want to lose my changes or something like git checkout . if I don't care about locally modified files. IMO much more simple than reset --hard, clean... and all this stuff more suited to leave the branch as in remote, including commits, untracked files, rather than just solving a locally modified file.

guillem
  • 2,768
  • 2
  • 30
  • 44
1

Once you do git pull, you will get list of files that are not matching. If the number of files is not very large then you can checkout those files, this action will overwrite those files.

git checkout -- <filename>

I usually do it if for quick check I modify local files on server (no recommended and probabaly reason behind you getting this issue :D ), I checkout the changed files after finding solution.

Ashutosh Nigam
  • 868
  • 8
  • 27
1

For those who don't like reset, I like this approach:


git checkout branchname      # go to your branch
git fetch origin branchname  # fetch the remote
git checkout -b backup       # optionally, mark your remote as a backup
git branch -f branchname origin/branchname # force your local branch to be equal to the fetched origin/branchname


Frederik Bode
  • 2,632
  • 1
  • 10
  • 17
1
git restore file_to_override_from_remote

git pull
FelipeGTX
  • 91
  • 1
  • 1
  • 8
0

Step 1. (optional)
From the root of your local repository, save a backup and empty the current folder:

mkdir -p ../<branch>-bkp && mv --backup=t * ../<branch>-bkp

Step 2. Download all files and folders of the branch from the remote repository:

git checkout <branch> && git add -A . && git reset --hard origin/<branch> && git pull

where you should replace <branch> with the name of the branch you want to overwrite.

Comments:

  • You may prefer to manually backup and remove the current files and folders instead of step 1.
    In fact, I recommend doing this with a file-handler in the GUI of your operating system.
  • If you skip step 1, beware: you will lose all work in the local repository!
  • Important: if you leave out git pull in step 2,
    you risk not getting the latest version from the remote repository!
    According to the second reference below, git reset --hard will
    reset the staging area and the working directory to match the most recent commit.
    My experience contradicts this claim!
  • If you run git reset --hard origin/<branch_to_overwrite> without first deleting all files and folders from your local repository, beware that any junk files still laying around may sneak into the remote repository at a later git push even if that was not your intention.
    The extra git add -A . in step 2 prevents this from happening if you choose to leave out step 1.

References:
https://gitforwindows.org/
https://www.atlassian.com/git/tutorials/undoing-changes/git-reset
https://www.atlassian.com/git/tutorials/rewriting-history/git-reflog

Henke
  • 4,445
  • 3
  • 31
  • 44
-1

I’ve tried most of what I could find here, none worked in my case.

What worked was git merge -X theirs

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sxilderik
  • 796
  • 6
  • 20
-4

You could try git pull --force or maybe stash your commits by using git stash and then running git pull.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ultan Kearns
  • 115
  • 7
  • 1
    This doesn't work. `fatal: refusing to merge unrelated histories` – Wyck Aug 23 '19 at 15:49
  • 1
    `Automatic merge failed; fix conflicts and then commit the result.` – Mutoh Jan 10 '20 at 16:32
  • 1
    No: `error: The following untracked working tree files would be overwritten by merge:` - i don't care about those files. If it where only two or three I would just delete them. But there are so many. – Martin Aug 20 '20 at 06:40
  • 2
    This worked nicely for me! What's going on? – EyesBear Jul 05 '21 at 18:46