How to Merge Two Git Repositories

  1. Steps to merging two repositories
    1. Adding remote URLs
    2. Combining files and folders
    3. Viewing history
  2. The git remote Command
  3. Merging Process

Here, you will figure out how to merge two repositories into a single one without losing the commit history. You can use the technique below in case of having two similar repositories and with both maintainers coming together to merge it.

Steps to merging two repositories

Assume we have two repositories: repo-1 and repo-2 and the repo-3 where you want to merge the repositories. Let’s consider that you are in the directory repo-3, where you want to merge the repositories. Suppose that you want to merge the master branches.

Adding remote URLs

As a first step, let's use the git remote add command with -f attribute to add a remote for the repo-1, naming it remote-1:

git remote add -f remote-1 <repo-1-URL>
With -f option, git fetch <name> is run immediately after the remote information is set up.

You should repeat the same steps for repo-2:

git remote add -f remote-2 <repo-2-URL>

Combining files and folders

Now, the time has come for combining the files of the remote-1 with the current branch of repo-3:

git merge remote-1/master --allow-unrelated-histories
You should add --allow-unrelated-histories so as Git won’t refuse to merge unrelated histories.

Next, you should merge the master branch of the remote-2:

git merge remote-2/master --allow-unrelated-histories
Note that conflicts can occur after running the command above. You need to resolve and commit the merge.

Viewing history

As a final step run git log command in your terminal to see merged commit history:

git log

The git remote Command

The git remote command is used for creating, viewing, and removing connections to other repositories. Remote connections are considered to be bookmarks in other repositories, which are convenient names used for referencing URLs that are not convenient enough. Using the git remote add command will add a new remote connection to a remote repository. Executing the git remote add command, a new connection record will be created to a remote repository.

Merging Process

The git merge command is used the independent lines of development into a single branch. The git merge command works with the git checkout command to select the current branch. The git checkout -b argument creates a new branch and directly switch to it.

The primary use of git merge is to merge two branches. It is also used to combine multiple commits into one history. It takes two branch tips and finds a common case commit between them. The common base commit creates a new commit that merges the changes in the sequence of each merge commit.


Do you find this helpful?

Related articles