How to Merge Unrelated Histories in Git
Table of contents⌗
Introduction⌗
Some times when you start working on a new project, you will create the repository for the code on GitHub first. Then you will work offline in your computer for a while as you still commit your work to git.
When you are ready to get your work to GitHub, you often encounter the error:
fatal: refusing to merge unrelated histories
Error redoing merge 1jhdf9dsf88734832908403023ksdfois
This error means that you are trying to get two branches (the one created in the
repository in GitHub and the one created locally in your project when you ran
git init
to initialize git in the project) with different histories merged.
This is not allowed.
However, the git
project has a flag that allows you to take your current
working branch, and force merge that history to be the main one for the
project.
Step by step fix⌗
First, you want to ensure that the branch you are overwriting has content that you don’t need or you have in your current branch.
This is because you’re going to lose the history of the other branch and you might not be able to recover it.
Next, you ensure you have all the work in the current branch committed.
git add .
git commit -m "Most recent changes of the project"
Lastly, you will pull in the changes from the project upstream and merge the
two histories by allowing unrelated histories. You do this by added the option
--allow-unrelated-histories
.
git merge origin master --allow-unrelated-histories
Conclusion⌗
I have shown you how to merge two unrelated histories using the
--allow-unrelated-histories
option.
Notes⌗
The --allow-unrelated-histories
option can be used when you do a git pull
or git push
commands. All you need to do is append the option when performing
any of these commands.