Hit enter after type your search item

How to forcefully pull / overwrite local files in Git?

In our other tutorials, we saw how to use the command for git push with force option if simple push command is generating errors or warnings. For example:

What if you require Git pulling the remote files/updates and Git is generating a conflict error or warning and you want to do it in any way.

This tutorial lists two ways of doing Git pull force as described below.

First way: Using the fetch and reset commands

Generally, if there is no conflict then the simple pull command works:

$ git pull origin master

Where you may use any repository name instead of origin and any other branch name instead of master.

The issues come when this command returns a conflict error message and does not complete the pull request. For example, the remote repository contains a file “tst1.txt”. The content of this file (for our demo) is:

“Some content for the demo purpose”

The same file exists in our local repo i.e. tst1.txt with this content:

“Hello, this is pull test”

Suppose, you have added this file in the master branch:

$ git add tst1.txt

And also committed:

$ commit -m “tst1.txt file added”

Now, if you run this command:

$ git pull origin master

Then, Git will return an error message of conflict like this:

Git pull conflict

This is because the content of two files differs while the file names are same. Consider the text files as your routine code files and that things happen while multiple programmers are using this.

Now, if you want to overwrite the content of the local file by the remote repository’s file, this is how you may do this.

Running the fetch command

The fetch command downloads all registered remotes and their branches. So rather than downloading all remotes and branches, you may download the specific branch. For example, if your target branch is master then execute this command:

$ git fetch origin master

At this stage, if you look at the text file’s (tst1.txt) content it should show something like this:

Run this command for overwriting the local file’s content by remote file:

This should output the following message:

If you look at the tst1.txt file content again, it should only show the remote file’s content i.e.

“Some content for the demo purpose”

In that way, you have overwritten the content of the local file(s) by remote files.

Second way – using the reset / pull commands

The reset command is basically used to set the current HEAD to the specified state. So, you may set the HEAD to initial state and remove all commits. Alternatively, just keep the .git directory in your local repo by this command:

$ git reset –hard HEAD~3

Where 3 represents the commit number where you want to revert back. Depending on your repo, specify the number.

Now run the pull command:

$ git pull origin master

Your set repository should be updated by the remote repo.

This div height required for enabling the sticky sidebar