How to Force Git Pull to Override Local Files

You may encounter a conflict issue when several users are working on the same files and folders. There are cases when you want to force pull to overwrite the local changes on the remote branch. In this snippet, you will find out how to force git pull in case of untracked files which will be overwritten.

  • Firstly, fetch all branches with the git fetch command. The git fetch command downloads commits, files and references from a remote repository into the local repository without merging and rebasing anything.
    git  fetch all branches
  • Then, run the git reset command to reset the master branch to what you fetched. The ---hard flag is used to change all the files in the working tree for matching the files in origin/master. Using the --hard option will delete any unpushed local commits and all local changes will be lost.
    git reset --hard origin/master
  • Then, run the git stash command to save all untracked files into the stash. Next, use git stash list for deleting specific stashed changes (or run git stash drop).

Maintain Current Local Commits

You can maintain current local commits by creating a branch from master before running git reset :

git checkout master
git branch new-branch-to-save-current-commits

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

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

Uncommitted changes even staged ones will be lost. Be sure to stash and commit anything you need by running the following:

git stash

Then, re-apply the uncommitted changes:

git stash pop

Using git pull

The git pull command fetches and downloads content from the remote repository and integrates changes into the local repository. It is used to update the current local working branch and the remote tracking branches for other branches. The git pull command is called as the combination of git fetch followed by git merge.

If there are uncommitted changes, merging via git pull will fail and the local branch will be untouched. For this reason, first commit your changes in a branch then pull the new commits from a remote repository.

Do you find this helpful?

Related articles