Git - How to force a git pull and overwrite local changes

In this post we will use a newly created remote repository and two local repositories cloned from that remote. We will then push a change and overwrite local uncommitted changes in the other. In short you are likely looking for these commands:

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

You can follow the step by step guide for more details on the situation and how/when to use the above.

Step by step

We start by setting up these two repositories by cloning remote, the first:

mkdir local-repo1
cd local-repo1
git clone <repoUrl>

and the second:

mkdir local-repo2
cd local-repo2
git clone <repoUrl>

We then add a file in repo one:


and commit and push it:

git add .\my-test-file.txt
git commit -m "this file we will pull in the other repo"
git push

We then pull this file in the other repo:

git pull

And we proceed to change the file:


and push these changes:

git add .\my-test-file.txt
git commit -m "changes from secnd repo"
git push

We then make some changes in the first repo without pulling the changes we just made:


What we have now are changes remotely (pushed by the second branch) that have never been pulled in the first repository. At the same time we have made uncommitted local changes in the first repository. If we use git pull we will see the following error:

error: Your local changes to the following files would be overwritten by merge:
Please commit your changes or stash them before you merge.

Now this is what it is all about. In this scenario we do not care for our own local changes, we just want what is on remote. If we wanted to merge the changes we would commit and pull, but for overwriting we will instead use the following commands:

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

The git fetch command fetches remote changes such as commits and branches but it does not change or merge it into your local files. You can see this as your local becoming aware of the remote changes. git reset resets to a specific commit or using origin/master to the newest commit. It basically means "overwrite my local branch changes with master". You can also use git reset --hard origin/<branch-name> to reset to another branch.

When running the above command we will see "HEAD is now at a834fa3 changes from secnd repo" which is the commit from the other repository - the most recent one on remote and the file now looks like this:


We can now continue from here, after having thrown away our other changes.

That is all

I hope you found this step-by-step guide helpful, feel free to leave a comment down below!