How to sync the fork repository with the main repository in Git?

Published October 20, 2020

To sync a forked repository with the main remote repository in Git. First, you need to fetch all the latest commits and branches from the remote main repository.

Step 1: Check if the main repository is added as a pointer!

Before starting we need to make sure that we have a pointer to the main repository to fetch the latest commits.

We can check this using this command,

git remote -v

It may show something like this,

origin  https://github.com/<YOUR_USERNAME>/<YOUR_FORKED_REPOSITORY_NAME>.git (fetch)
origin  https://github.com/<YOUR_USERNAME>/<YOUR_FORKED_REPOSITORY_NAME>.git (push)

The origin here means our fork of the main repository which is not what we want (Because the fork contains only our latest commits. 🙄).

So There should be a pointer to the main repository.

Let's call the main repository upstream and let's add a pointer to the main repository using this command,

git remote add upstream <MAIN_REPOSITORY_GIT_URL>

You need to replace <MAIN_REPOSITORY_GIT_URL> with the main repository Git URL.

This will add the main repository.

Now if you do

git remote -v

again.

It will show the new upstream also.

origin  https://github.com/<YOUR_USERNAME>/<YOUR_FORKED_REPOSITORY_NAME>.git (fetch)
origin  https://github.com/<YOUR_USERNAME>/<YOUR_FORKED_REPOSITORY_NAME>.git (push)

upstream  https://github.com/<MAIN_REPOSITORY_USERNAME>/<MAIN_REPOSITORY_URL>.git (fetch)
upstream  https://github.com/<MAIN_REPOSITORY_USERNAME>/<MAIN_REPOSITORY_URL>.git (push)

Yay. 🌟 Now the upstream is added.

Step 2: Get the latest commits

To get the latest commits from the upstream (the main repository) you need to use this command,

git fetch upstream

This will fetch all the latest commits, branches, etc from the main repository.

Step 3: Merge the main or master branch of upstream (main repository)

Info: master branch name is now main if you are using Github.

To merge the main or master branch of the main repository you can use this command,

git merge upstream/main


# OR

# git merge upstream/master

Now you are synced with the main (or master) branch of upstream.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter