While git doesn’t actually have a git pull --force
command, it’s possible to overwrite your local branch to pull upstream changes by jumping to the latest commit on origin/main
.
Fetch remote changes
The first step in “force pulling” your local branch is to fetch the latest changes from the remote:
git fetch --all
The fetch
command fetches all of the latest upstream changes but does not merge them with your local branches.
Create a backup branch
While this step is not necessary, it’s highly recommended to mitigate any unintentional data loss.
Create a copy of the branch you intend on “force pulling”:
git branch <backup_branch_name>
This will preserve a copy of the current state of the local branch just in case you delete anything unintentionally.
Jump to the latest commit
Next use the git reset
command with the --hard
flag to reset your local index and working tree, and point them to the latest commit of your remote branch.
Another warning: this is a destructive operation. Per the documentation:
Any changes to tracked files in the working tree since
<commit>
are discarded. Any untracked files or directories in the way of writing any tracked files are simply deleted.
Once you are ready to overwrite your existing local branch, run:
git reset --hard origin/<branch_name>
This command resets your current branch to exactly match the remote branch, discarding any local changes or commits.
Stashing local changes
In cases where you want to keep your local changes while overwriting the rest of the branch with the latest changes you can use git stash. This command saves all your local changes and reverts the working directory to match the HEAD
commit.
In order to save your local changes first run:
git stash
Then, once you’ve completed your “force pull” according to the previous steps, run:
git stash pop
This command re-applies your local changes on top of the current working tree state. This may result in merge conflicts between the stashed changes and the current local state.
Once you have resolved these conflicts, you're all set. You've force pulled remote changes into your local branch while preserving your local changes.
For further reading on these operations please see the official documentation on fetch, reset, branch, and stash.