In our other tutorial, we saw how to use the command for git push with force option if a simple push command is generating errors or warnings. For example:
$ git push origin master --force
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:
Where you may use any repository name instead of origin and any other branch name instead of master.
For example, the remote repository contains a file “tst1.txt”. The content of this file (for our demo) is:
The same file exists in our local repo i.e. tst1.txt with this content:
Suppose, you have added this file in the master branch:
And also committed:
Now, if you run this command:
Then, Git will return an error message of conflict like this:
This is because the content of two files differs while the file names are the same.
Consider the text files as your routine code files and things happen while different programmers are using this.
Now, if you want to overwrite the content of the local file with the remote repository’s file, this is how you may do this.
Running the fetch command
$ git fetch --all
At this stage, if you look at the text file’s (tst1.txt) content it should show something like this:
<<<<<<< HEAD Hello, this is pull test ======= Some content for the demo purpose >>>>>>> 628cb6aea41a1319ce86202d6b31714e26bf95c1
Run this command for overwriting the local file’s content by remote file:
$ git reset --hard origin/master
This should output the following message:
HEAD is now at 628cb6a Create tst1.txt The 62**** code should vary if you try this in your system.
If you look at the tst1.txt file content again, it should only show the remote file’s content i.e.
In that way, you have overwritten the content of the local file(s) by remote files.
Second way – using the reset / pull commands
So, you may set the HEAD to the initial state and remove all commits. Alternatively, just keep the .git directory in your local repo by this command:
Where 3 represents the commit number where you want to revert. Depending on your repo, specify the number.
Now run the pull command:
Your set repository should be updated by the remote repo.