MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Git Tutorials: Merge code between multiple repos

To merge code from one Git repository into another, add the second repository as a remote, fetch it, and merge its branch into your target branch with --allow-unrelated-histories. This keeps the full commit history from both repositories. Below the original steps you'll find a corrected version of the merge command, which is reversed in step 4, plus help with conflicts, a way to merge into a subdirectory, and fixes for common errors.

It is something you can do locally though, from your machine, the following way:

1. Assume you have repos https://bitbucket.org/my-workspace/repo-1/ and https://bitbucket.org/my-workspace/repo-2/, and you want to merge code from repo-2 to repo-1

Navigate to your local clone of repo-1

2. Add the second repo as a remote with a command like the following (I’m adding the SSHL URL; if you don’t use SSH, you can replace with the HTTPS URL:

git remote add second_remote git@bitbucket.org:my-workspace/repo-2.git

then

git fetch --all

3. Then create (in repo-1) a branch that tracks the remote branch from repo-2 you want to merge, named e.g. feature2-branch

git checkout -b feature2-branch --track second_remote/feature2-branch

4. If you wang to merge that to master branch of repo-1, then you can do

git merge master --allow-unrelated-histories

The –allow-unrelated-histories will be necessary if the repos have no common history, otherwise Git will refuse to make the merge.


What this technique does and when to use it

Git can fetch from any number of remotes, not just origin. When you add a second repository as a remote, its branches and commits are downloaded into your local repo. You can then merge them like any other branch. The result is one repository with the commit history of both.

  • Consolidating repos: combining two related services or libraries into one repository (monorepo migration).
  • Porting a feature: bringing a branch from a fork or a sibling repository into your own.
  • Rescuing work: pulling commits out of an archived or duplicated repository without losing authorship and history.

If the two repositories were never forks of each other, they share no common commit. Git refuses to merge them unless you pass --allow-unrelated-histories. If one repo is a fork of the other, they already share history and the flag is not needed.

Corrected step-by-step workflow

In step 4 of the example above, git merge master is run while feature2-branch is checked out. That merges master into feature2-branch, which is the opposite of the goal. To bring repo-2's code into repo-1's main branch, check out the target branch first, then merge the incoming branch into it. The full sequence:

# 1. Work inside a clean, up-to-date clone of repo-1
cd repo-1
git status                      # should report a clean working tree
git switch main                 # or: git checkout master
git pull origin main

# 2. Add repo-2 as a second remote (SSH or HTTPS URL)
git remote add second_remote git@bitbucket.org:my-workspace/repo-2.git
# HTTPS alternative:
# git remote add second_remote https://bitbucket.org/my-workspace/repo-2.git

# 3. Download repo-2's branches and commits
git fetch second_remote

# 4. Merge the wanted branch from repo-2 into repo-1's main branch
git merge second_remote/feature2-branch --allow-unrelated-histories \
  -m "Merge feature2-branch from repo-2"

# 5. Publish the result
git push origin mainCode language: PHP (php)

You don't need to create a local tracking branch (step 3 above) just to merge. git merge second_remote/feature2-branch merges the remote-tracking ref directly. A local branch is only useful if you want to inspect or change repo-2's code before merging. If you want one, use git switch -c feature2-branch --track second_remote/feature2-branch, then switch back to main before running the merge.

Note: Use the branch names that actually exist. Many repositories now use main instead of master. Run git branch -r after fetching to list the branches available on second_remote.

Verifying the result

Check that the remote was added and the merge commit has two parents:

$ git remote -v
origin         git@bitbucket.org:my-workspace/repo-1.git (fetch)
origin         git@bitbucket.org:my-workspace/repo-1.git (push)
second_remote  git@bitbucket.org:my-workspace/repo-2.git (fetch)
second_remote  git@bitbucket.org:my-workspace/repo-2.git (push)

$ git log --oneline --graph -n 15
# Expect a merge commit at the top with two lines of history
# joining it: one from repo-1 and one from repo-2.Code language: PHP (php)

git log --author="Name" or git blame on a file from repo-2 should show the original authors and dates. This confirms that history was kept and not squashed.

Handling conflicts between unrelated repositories

Unrelated repositories often contain files with the same path, such as README.md, .gitignore, package.json or CI configuration. Git reports these as both added conflicts because neither side has a common ancestor version.

  1. Run git status to list the conflicting files.
  2. Open each file, resolve the <<<<<<<, ======= and >>>>>>> markers, and keep the content you need from both sides.
  3. To keep one side entirely, use git checkout --ours path/to/file (repo-1) or git checkout --theirs path/to/file (repo-2).
  4. Stage the resolved files with git add path/to/file.
  5. Finish with git commit. To abandon the whole merge instead, run git merge --abort.

If many files collide, it is usually cleaner to merge repo-2 into its own subdirectory, as shown in the next section.

Merging another repository into a subdirectory

For monorepo migrations you usually want repo-2's files under a folder such as repo-2/ instead of mixed into the root. There are two common approaches.

Option 1: git subtree. This is included with most Git installations. It adds the content under a prefix and keeps history, unless you pass --squash:

git fetch second_remote
git subtree add --prefix=repo-2 second_remote main

Option 2: rewrite paths with git filter-repo, then merge. This is a separate tool that you install yourself. It rewrites repo-2's history so every commit already lives under repo-2/, which makes git log and git blame on the moved files work naturally. Always run it on a fresh, throwaway clone:

git clone git@bitbucket.org:my-workspace/repo-2.git /tmp/repo-2-rewrite
cd /tmp/repo-2-rewrite
git filter-repo --to-subdirectory-filter repo-2

cd /path/to/repo-1
git remote add repo2_local /tmp/repo-2-rewrite
git fetch repo2_local
git merge repo2_local/main --allow-unrelated-histories -m "Import repo-2 into repo-2/"
git remote remove repo2_localCode language: PHP (php)

Note: git filter-repo rewrites commit IDs. Never run it in a clone that you will push back to the original repo-2 remote.

Common errors and fixes

ErrorCauseFix
fatal: refusing to merge unrelated historiesThe repos share no common commitAdd --allow-unrelated-histories to the merge command
error: remote second_remote already exists.The remote name is already in useUse another name, or update it with git remote set-url second_remote <url>
Permission denied (publickey)No SSH key with access to repo-2 is loadedAdd your SSH key to the Bitbucket/GitHub account, or use the HTTPS URL
merge: second_remote/feature2-branch - not something we can mergeThe branch wasn't fetched or the name is wrongRun git fetch second_remote and check names with git branch -r
! [rejected] main -> main (fetch first) on pushorigin/main moved while you were mergingRun git pull origin main, resolve any conflicts, then push again

Best practices

  • Do the merge on a new branch (for example git switch -c merge-repo-2) and open a pull request instead of pushing straight to main. This gives reviewers and CI a chance to catch problems.
  • Before you start, check that both working trees are clean and both repos are up to date.
  • Remove the extra remote when you are done with git remote remove second_remote, so no one pushes to it by mistake.
  • Before running the merge, search repo-2 for secrets or large binaries. Once merged, they become part of repo-1's history and are hard to remove.
  • Use descriptive merge commit messages that name the source repository and branch, so the import is easy to find later.

For branching strategies around merges like this, see the Git Workflow Master Tutorial.

Frequently asked questions

Does merging two Git repositories keep the commit history?

Yes. Adding the second repo as a remote and running git merge --allow-unrelated-histories keeps every commit, author and date from both repositories. History is only lost if you squash, for example with git subtree add --squash.

Why does Git say refusing to merge unrelated histories?

Since Git 2.9, Git refuses by default to merge branches that have no common ancestor, to prevent accidental merges. Add --allow-unrelated-histories when you really do mean to combine two independent repositories.

Can I merge only one folder from another repository?

Yes. In a fresh clone of the source repo, run git filter-repo --path folder/ to keep only that folder's history. Then add that clone as a remote and merge from it with --allow-unrelated-histories.

Do I need to create a local tracking branch before merging from another remote?

No. After git fetch second_remote, you can merge second_remote/branch-name directly into your checked-out branch. A local tracking branch is only useful if you want to review or change the code first.

How do I undo a merge from another repository?

If the merge isn't finished yet, run git merge --abort. If it is committed but not pushed, git reset --hard ORIG_HEAD returns you to the state before the merge. If it has already been pushed, use git revert -m 1 <merge-commit> instead of rewriting shared history.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Git Lab Exercise & Assignment: Branching & Merging & Conflicts: Part – 4

This lab has you create a merge conflict on purpose: two branches change the same line of one file, and you then inspect the conflict, look at…

Read More

Git Training Roadmap: Practical Curriculum, Labs, and Team Workflow

A modern, hands-on Git training blueprint for DevOps and engineering teams. Use this curriculum, workflow, and command labs to build real-world Git skills quickly.

Read More

Gitflow Branching Model: Practical Guide to Feature, Release, and Hotfix Branches

Learn how the classic Gitflow model organizes development with long-lived and short-lived branches. This guide covers branch rules, workflow, and production-ready Git command examples.

Read More

Git Branching and Merging Best Practices for DevOps Teams

This guide explains how DevOps teams can use Git branching and merging patterns to ship safely without slowing delivery. It includes a workflow diagram, model comparisons, and practical commands you can standardize.

Read More

SCM Process in DevOps: Practical Workflow and a Change-Aware smartBuild Pattern

This revised guide explains how to run an effective SCM process and apply a smart build approach that only builds and tests impacted components. It also preserves the original slide and attribution while adding practical DevOps implementation guidance.

Read More

Source Control Branching Model Master Tutorial

From Beginner to Advanced: A Complete One-Stop Guide for Designing Branching Strategies 1. What is a source control branching model? A source control branching model is the…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x