git,

Merging two or multiple Git repos

Oct 21, 2022 · 1 min read · Post a comment

Here’s a fun Git exercise you could try if you have few multiple repos to spare. Try to merge two or more repos in a single git repository. It’s quite easy if you don’t care about the Git commit history at all.

Let’s take two Git repos as an example: repo App1 and repo App2. What we want to achieve is to merge repo App2 into App1.

Prerequisites

  • Git

Solution

Step 1. Clone the App1 repo if you haven’t done already and cd into the working directory.

git clone [email protected]:devcoops/app1.git && cd app1

Step 2. Add the remote URL of repo App2.

git remote add -f app2 [email protected]:devcoops/app2.git

Step 3. Verify Git remotes.

git remote -v

Step 4. Fetch App2.

git fetch app2

Step 5. Now merge whatever branch you want to merge. Let’s take the main branch for instance.

git merge app2/main --allow-unrelated-histories

Step 6. Last but not least, confirm the merge by listing the Git commits.

git log

Note(s):

  • --allow-unrelated-histories is a must since you’ll most probably run into the following error: Fatal: refusing to merge unrelated histories.
  • Merge conflicts could appear if you have files with identical names under the same directory path.

Conclusion

To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git