1. Overview

In Git, there are situations when the branches don’t have a common history base. So, if we try to merge them, we get the “refusing to merge unrelated histories” error. In this tutorial, we’ll discuss how to fix this error and how to avoid this error in future projects.

2. Why Branches Can Have Unrelated Histories?

Let’s look at the scenario when the branches have unrelated histories. The most common reason for having an unrelated history base is for starting the branches independently of each other. For example, if we start a new Git project on a local machine and then connect it to a remote GitHub branch, these branches would have different history bases.

The only exception is when one of the branches has no commits in it. In this case, they should merge without a problem. Otherwise, we’ll get the “refusing to merge unrelated histories” like in the following example:

$ git pull origin main
...
fatal: refusing to merge unrelated histories

As we can see, we couldn’t use the git pull command to merge the branches with uncommon history.

3. How to Fix the Error

To fix the above error, we need to use the option –allow-unrelated-histories after the git pull <remote> <branch> command, where

  • <remote> is the remote repository URL or its short-name origin
  • <branch> is the branch name that we’d like to merge

For example:

$ git pull origin main --allow-unrelated-histories

The –allow-unrelated-histories option will tell the Git that we allow merging branches with no common history base, which then should finish the merge without errors. We should note that for the Git version 2.9 or older, this option is not necessary, and our merge should work without it. To check the Git version, we can use the git –version command.

4. How to Avoid the Error in the Future

Typically, it’s not the best practice to create a local repository branch independently of the remote repository. A more reliable way is to download the remote repository to the local machine using the git clone command, like this:

$ git clone <repo_url>

This way, we copy the repository from the remote server, and the commit history base remains the same for both remote and local branches.

5. Conclusion

In this tutorial, we discussed how to merge branches when Git is refusing to merge unrelated histories. We firstly looked at when this error can happen. Then, we used the –allow-unrelated-histories option to fix it. And finally, we learned how to avoid this error in future projects.

Comments are closed on this article!