How to Replace a Branch with Another Branch in Git

A while back, I had a master branch and a my_branch branch.

Out of bad practice, the my_branch branch had effectively become the main repository, or the “working master branch”.

I wanted to overwrite my master branch with the my_branch branch entirely.

Merging branches

This solution will retain all commits and history in master.

git checkout my_branch
git merge -s ours master
git checkout master
git merge my_branch

If the first merge returns an error like the following:

fatal: refusing to merge unrelated histories

Then, you can add a flag to allow these merges to go through.

git merge --allow-unrelated-histories -s ours master

Read more about the ours strategy.

Renaming branches

Another way to go about this issue is to rename the branches.

This solution will remove all commits and history in master.

If the entire master branch is replaceable, then this will be a simple solution.

git branch -m master old_master
git branch -m my_branch master
git push -f origin master