When working with multiple codebases, you may reach a point where you want to merge two repositories into one. Whether it’s consolidating microservices, archiving old projects, or combining forks, GitHub offers a way to do this without losing history.
In this post, you’ll learn how to merge two GitHub repositories safely and effectively using the Git command line.
🧭 Use Case Scenarios
You might want to merge repositories if:
- You’re combining microservices into a monorepo.
- You forked a repo and developed it independently.
- You’re consolidating multiple projects under one namespace.
⚙️ Pre-Requisites
- Git installed on your local machine
- Access to both GitHub repositories
- Basic knowledge of Git commands
🛠️ Steps to Merge Two GitHub Repositories
Let’s say we have:
Repo-A(main repo, where everything will be merged)Repo-B(repo to be merged intoRepo-A)
We’ll merge Repo-B into a subfolder in Repo-A so we preserve history and maintain structure.
✅ Step 1: Clone the Main Repository
git clone https://github.com/your-username/repo-a.git
cd repo-a
✅ Step 2: Add the Second Repository as a Remote
git remote add repo-b https://github.com/your-username/repo-b.git
Then fetch it:
git fetch repo-b
✅ Step 3: Create a Merge Folder (Optional but Recommended)
To keep the content organized:
mkdir repo-b-folder
✅ Step 4: Merge Repo-B into a Subdirectory
Use git read-tree to preserve history and structure:
git read-tree --prefix=repo-b-folder/ -u repo-b/main
Replace
mainwith the default branch ofrepo-bif different.
✅ Step 5: Commit the Merge
git commit -m "Merged repo-b into repo-a under repo-b-folder/"
This keeps the full history of repo-b intact.
✅ Step 6: Push the Changes to GitHub
git push origin main
Now repo-a contains the full content of repo-b, and you’ve preserved commit history inside a dedicated folder.
🧹 Optional Cleanup
If you no longer need repo-b as a remote:
git remote remove repo-b
You can also delete the original repository on GitHub if consolidation is complete.
✅ Summary
| Step | Action |
|---|---|
| 1 | Clone the main repo (repo-a) |
| 2 | Add repo-b as a remote |
| 3 | Fetch and merge repo-b into a subdirectory |
| 4 | Commit and push to GitHub |
🔒 Best Practices
- Always back up both repositories before merging.
- Test the merged repo locally before pushing changes.
- Use clear commit messages to indicate where the merge came from.
- Consider documenting the merge process in your repo’s README.
📌 Conclusion
Merging repositories in GitHub is a powerful technique when done carefully. Whether for consolidation, cleanup, or collaboration, following these steps ensures you maintain version history and clarity in your project.