How to Force Git Pull to Override Local Files
This tutorial will show you how to force git pull in case of untracked files which will be overwritten. Find important tips to avoid unwanted mistakes.
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. Note that git pull does not have a --force flag for overwriting local changes; instead, you must reset your local branch and clean untracked files.
Steps to force 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 with the remote.
Fetching branches
Firstly, fetch all branches with the git fetch command. The <kbd class="highlighted">git fetch</kbd> command downloads commits, files and references from all remotes into the local repository without merging and rebasing anything.
git fetch --all
git fetch --allResetting changes
Then, run the git reset command with the <kbd class="highlighted">--hard</kbd> flag to change all the files in the working tree to match the files in origin/master (suppose, the name of remote is origin, which is by default). Using the <kbd class="highlighted">--hard</kbd> option will delete any unpushed local commits and all local changes will be lost.
git reset --hard origin/<branch-name>
git reset --hard origin/<branch-name>Note: git reset --hard only affects tracked files. To remove untracked files and directories, run git clean -fd.
Maintaining current local commits
You can maintain current local commits by creating a branch from your current branch before running <kbd class="highlighted">git reset</kbd>:
git reset and clean untracked files
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.
Uncommitted changes
If you have uncommitted changes, even if you have staged them, they will be lost after running the <kbd class="highlighted">git reset</kbd> 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 separate location and clean your local repository.
git stash
git stash- Later, whenever you would like to apply your saved changes, you can run the following command:
git stash pop
git stash popUsing 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 <kbd class="highlighted">git pull</kbd> command is called as the combination of <kbd class="highlighted">git fetch</kbd> followed by git merge.