git merge repositories

How to Merge Two Git Repositories

Git is a great version control system that allows you to easily develop large and complex projects in an organized and distributed manner. Each project is called as a git repository (code repository). Sometimes you may have developed a project as a separate Git repository. And then you may want to merge it with a larger repo without losing history of either repositories. In such cases, you will need to merge one repository with another. Typically, we merge two or more branches in one repository but this needs a different approach. In this article, we will learn how to merge two git repositories.


How to Merge Two Git Repositories

Here are the steps to merge two git repositories. Let us say you have two repositories repoA and repoB and you want to merge repoA into repoB.

1. Go to RepoB

First, you need to navigate to repository into which you will be merging the other repository. That is repoB in our case.

$ cd path/to/repoB

2. Add Remote URL

From repoB, you need to add remote URL to the other repository that you want to merge, that is, repoA.

$ git remote add repoA /path/to/repoA

Now you can use repoA identifier to access the repoA’s contents.

3. Fetch RepoA

Then you need to download repoA into repoB using git fetch command.

$ git fetch repoA --tags

4. Merge repositories

Then you need to merge the downloaded repoA content into repoB using git merge command. Here is the command to merge the master branch of repoA with the master branch of repoB. It is important to use –allow-unrelated-histories option so that the histories of neither repository is disturbed.

$ git merge --allow-unrelated-histories repoA/master 

Please note, –allow-unrelated-histories option exists only since git >=2.9. If you want to merge another branch of repoA you need to specify as shown below. Replace <branch_name> with the branch name that you want to merge.

$ git merge --allow-unrelated-histories repoA/<branch_name>

If you want to merge repoA with another branch of repoB, check out to that branch first before you run the above git merge command.

Finally, remove the remote handle.

$ git remote remove repoA

If you want to put repoA into a subdirectory, then run the following command before you run the above command to merge repoA with repoB.

$ cd path/to/repoA
$ git filter-repo --to-subdirectory-filter repoA

In this article, we have learnt how to merge two git repositories.

Also read:

How to Setup Git Username & Password for Different Repos
How to Reset Git Credentials
How to Add Images to README.md in GitHub
How to Cache HTTPS Credentials for Pushing Commits
How to Change Author & Committer in Git

Leave a Reply

Your email address will not be published.