Git: How do I force “git pull” to overwrite local files?

Summary

 It is very important to note if you want to overwrite local files that if you make any changes in the local file then it will be lost. And With or without --hard option, if you don’t push the local commit it will get lost.

And if there are some files that are not tracked by Git, such as the files which are in the user content. So that files will not get affected.

Firstly we can do run a fetch to update all origin/<branch> refs to latest:

git fetch --all

So if you want to back up the branch which is currently in use and that is :

git branch backup-master

At that time you have a total of two options and they are :

git reset --hard origin/master

 Or in case you are on some other branch:

git reset --hard origin/<branch_name>

Explanation:

So if you want to download the latest from remote without trying to merge or rebase anything use git fetch.

After that the git reset will reset the master branch. For what you just see or can be said fetched.   The --hard the option will change all files that you are working on so that they will be matched to 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

And once this all is done overwrite local files your old commits will be kept in the  new-branch-to-save-current-commits.

Uncommitted changes

Uncommitted changes, however (even staged), will be lost. Make sure to stash and commit anything you need. For that you can run the following:

git stash

And if you again apply to the uncommitted changes

git stash pop

 

Also read, Why are these datagrams reassembled to a single datagram.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *