How to force git pull to overwrite local repository files?

You can use git reset –hard <remote_name>/<remote_branch_name> command to force git pull to overwrite local repository files.

This is helpful when you are getting “error: Your local changes to the following files would be overwritten by merge” or “fatal: Need to specify how to reconcile divergent branches” messages during the pull and you want to discard your local repository changes and force pull your remote changes.

Example:

Create a new git local repository:

Create first commit in default branch of local repository:

Create a new empty git remote repository:

Clone the remote repository to some other place and push a change:

Next, move back to the previous git repository (myrepo1) and try to pull after some local changes:

Change an existing file (already indexed) and try to pull:

Observe: You will get an error “error: Your local changes to the following files would be overwritten by merge:“. Here you can either discard the local change or force pull, we will discard the local change and carry on.

Discard local change:

Create a new file (not indexed) in the working tree and try to pull:

Observe: This time you are able to pull as it does not impact any file in your working tree that is not yet indexed by git.

Discard local change:

Create a new file (not indexed) in staging area and try to pull:

Observe: This time you are able to pull as well as it does not impact any file in your staging area that is not yet indexed by git.

Discard local change:

Create a new file and commit (indexed) and then try to pull:

Observe: You get an error “fatal: Need to specify how to reconcile divergent branches”. Again you can either discard the change or force pull but unlike last time we are going to force pull this time to demonstrate how to force pull.

Force pull discarding/overwriting local changes: