How to Force Pull in Git

Azhar Bashir Khan Feb 02, 2024
How to Force Pull in Git

In this tutorial, we will learn about pulling changes from the remote repository forcefully in Git.

Sometimes, we may need to discard the local modifications and replace them with updates from the remote repository in a collaborative development environment.

We use the git pull command to fetch the changes from the remote repository to the local branch in the local repository.

The git pull command will succeed only if the changes in the local branch are behind the changes in the remote repository.

If the local branch and the remote repository changes have diverged and if we wish to discard the local changes, we need to forcefully do a git pull to overwrite the local changes,

We will now elaborate this with an example.

Using git fetch, git reset and git merge to Do a Forceful Pull of the Remote Changes in Git

The git pull command is not a single operation. The git pull command runs the command viz. git fetch to fetch the data from the remote repository, and then the command git merge to merge those changes into the local repository.

The git pull command thus runs the two commands as follows.

$ git fetch
$ git merge origin/$CURRENT_BRANCH

The git fetch command downloads the latest changes from the remote repository. It does not do any merge or rebase of the local repository.

The git merge command given above merges the changes from the remote repository, given by the alias origin, that have been added to the $CURRENT_BRANCH, which are not already present in the local branch in the local repository.

Thus, the git pull will fail if the local branch in the local repository is divergent from the branch in the remote repository.

We may have made some local changes to the files in the working tree of the local branch. Thus, this causes the git pull to fail.

We may now decide to discard the local changes in favor of the changes in the remote repository.

Thus, we need to pull the changes forcefully that will overwrite the local modifications.

We need to do as follows to achieve a forceful pull of the remote changes.

$ git fetch
$ git reset --hard HEAD
$ git merge origin/$CURRENT_BRANCH

The git reset command with the --hard option will reset the branch to what we just fetched. It will also discard any local changes to the tracked files, and the files that are not tracked will be deleted.

Thus, use this with caution, as any local changes will be lost.

Alternatively, we can save the local changes before pulling the changes. We can stash the changes using git stash along with the pull of the changes.

We can do as follows.

$ git fetch
$ git stash
$ git merge origin/$CURRENT_BRANCH
$ git stash pop

Thus, when we use git stash, we no longer need to do a git reset of the local branch of the local repository.

We used the git stash pop to get local changes from the stash.

Related Article - Git Pull