Fatal: Refusing to Merge Unrelated Histories Error in Git

  1. Common Scenarios of the fatal: refusing to merge unrelated histories Error in Git
  2. Resolve the fatal: refusing to merge unrelated histories Error in Git

This article outlines the steps needed to solve the fatal: refusing to merge unrelated histories error in Git. We usually encounter such an error when attempting to merge two unrelated Git projects into one branch.

It will pop up when the recipient branch has commits, and the clone has incompatible tags.

Common Scenarios of the fatal: refusing to merge unrelated histories Error in Git

Here are some cases where you will likely encounter the fatal: refusing to merge unrelated histories error in Git.

  1. You have a local repository containing commits and attempt to pull from an existing remote repository. Since the histories are different, Git does not know how to proceed.

    Hence the error message.

  2. Your .git directory is corrupted.

  3. When your branches are at different HEAD positions.

Resolve the fatal: refusing to merge unrelated histories Error in Git

We can resolve the error by allowing unrelated merging. We can do this by adding the --allow-unrelated-histories flag to the pull request, as shown below.

How to fix common errors in git
$ git pull origin master --allow-unrelated-histories

Git will allow you to merge branches with unrelated histories. It is pretty easy if your files do not conflict.

The above method is the easiest; however, there is a longer route to the same destination.

First, you will have to unstage all your current commits and stash them. You can then pull from the remote repo and apply the stash to the new clone.

This makes it easier to deal with merge conflicts in case they occur.

To unstage, all the files in the last commit, use the command below.

$ git reset HEAD~

Run the command below to stash the files.

$ git stash

Now you have a clean working tree, and you can run a pull request, after which you will unstash and apply the stashed changes to the working tree. You can run:

$ git stash pop

The command above will apply the stash and discard it. If you want to apply and keep the stash, you can run:

$ git stash apply

With that being said, what is the easiest way to avoid this error message?

Avoid pulling remote repositories into local branches containing commits. If you have to, create a new branch and manually pull and merge the changes.

In conclusion, the fatal: refusing to merge unrelated histories error occurs when we are attempting to merge branches with different commit histories. We have gone through the two ways to resolve the error and how to best avoid it.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Git Error

  • Fatal: The Remote End Hung Up Unexpectedly Error in Git
  • Troubleshoot Git Patch Error