How to Force Git Pull to Override Local Files
- Steps to forcing git pull to override local files
- Maintaining current local commits
- Uncommitted changes
- Using git pull
You may encounter a conflict issue when several users are working on the same files. There are cases when you want to force pull to overwrite the local changes from the remote branch.
Steps to forcing git pull to override local files¶
Let's find out how to force git pull to overwrite your local changes and fully match your local branch to the remote.
Firstly, fetch all branches with the git fetch command. The git fetch command downloads commits, files and references from all remotes into the local repository without merging and rebasing anything.
git fetch --all
Then, run the git reset command with the --hard flag to change all the files in the working tree for matching the files in origin/master (suppose, the name of remote is origin, which is by default). Using the --hard option will delete any unpushed local commits and all local changes will be lost.
git reset --hard origin/<branch-name>
Maintaining current local commits¶
You can maintain current local commits by creating a branch from your current branch before running git reset:
git checkout <branch-name> git branch <new-branch-to-save-current-commits> git fetch --all git reset --hard origin/<branch-name>
After running this, all of the old commits will be kept in <new-branch-to-save-current-commits> branch.
If you have uncommitted changes, even if you have staged them, they will be lost after running the git reset command. If you want to save your changes to use them later, you can act as follows:
- Run git stash to keep your local changes in a separated place and clean your local repository.
- Later, whenever you would like to apply your saved changes, you can run the following command:
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.