Skip to main content

Managing Multiple Git Repositories

When your codebase becomes too large to maintain in a single Git repository, you should consider using multiple repositories. This guide explains how to manage multiple Git repositories effectively.

Prerequisites

Before you start managing multiple repositories, ensure the following prerequisites are met:

  • Your public SSH keys (id_ecdsa.pub / id_rsa.pub / id_ed25519.pub, etc.) are added to your GitHub and GitLab profiles.
  • Your private SSH keys (id_ecdsa / id_rsa / id_ed25519, etc.) are added and persisted in your operating system's keychain.
  • Your SSH config file (~/.ssh/config) is properly configured with keys for GitHub and GitLab.

Example SSH config:

.ssh/config
Host github.com
Hostname github.com
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_ecdsa

Host gitlab.com
Hostname gitlab.com
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa

Or, for multiple users:

.ssh/config
Host github.com-user
HostName github.com
User git
IdentityFile /home/user/.ssh/id_ed25519

Host gitlab.com
PreferredAuthentications publickey
IdentityFile /home/user/.ssh/id_ed25519_2

Setting Up Multiple Repositories

  1. Initialize Git in a directory:
git init
  1. Connect Git to one remote repository (located on GitHub):
git remote add origin [email protected]:your-username/your-repo.git
  1. Rename the .git directory to something like .github:
mv .git .github
  1. Initialize Git again:
git init
  1. Connect Git to the other remote repository (located on GitLab):
git remote add origin [email protected]:your-username/your-repo.git
  1. Rename the .git directory to something like .gitlab:
mv .git .gitlab
  1. Verify that the current directory is connected to two different remote repositories:
git --git-dir=.github remote -v

Working with Multiple Repositories

  • Pull changes from remote repositories (GitHub and GitLab):
git --git-dir=.github pull origin main
  • Add a file to both repositories:
git --git-dir=.github add README.md
  • Commit changes:
git --git-dir=.github commit -m "Operational overview"
  • Push changes to the remote repositories:
git --git-dir=.gitlab push -u origin main

For frequent use, consider adding an alias in your shell configuration file (e.g., .zprofile, .bashrc, etc.):

export github="git --git-dir=.github"

This allows you to perform future operations, such as pulling, pushing, adding, and committing, more conveniently, like so:

github pull origin main

You can create similar aliases for other repositories as needed.