Merge two Git repositories into one

Sometimes, you wished you have created one single Git repo, instead of two separates. Merging two Git repositories into one can help to combine different projects into one larger project, or to combine the work of two teams into one version-controlled repository. It can also help to keep your work organized by having all of your related projects in one place.

Fortunately, it is possible to merge two repositories with only 5 steps. We’ll call repo1 the repository that you want to keep, and repo2 the repository that you want to merge into repo1.

  1. Clone the repo that you want to keep and navigate to its local directory:
    git clone <link-for-repo1>
    cd <repo1>
    
  2. Add repo2 as a remote branch (name it whatever you want) in the first repository, using the following command:
    git remote add <repo2-branch-name> <link-for-repo2>
    
  3. Fetch the latest changes from repo2 using the following command:
    git fetch <repo2-branch-name>
    
  4. Merge the changes from repo2 into repo1, for example in branch master, with:
    git checkout master
    git merge <repo2-branch-name> --allow-unrelated-histories
    

After running these commands, your destination repository will contain all of the changes from both repositories. You can then push these changes to the remote repository.

It’s important to note that this process can potentially create conflicts if there are overlapping changes between the two repositories. In this case, you will need to resolve the conflicts manually before you can complete the merge (use git status).