Skip to main content

Git Multiple Repo

Pre-requisites:

  • Public SSH keys (id_ecdsa.pub / id_rsa.pub / id_ed25519.pub , etc.) are present in your GitHub and GitLab profiles

  • Private SSH keys (id_ecdsa / id_rsa / id_ed25519 , etc.) are added and persisted in your OS's keychain

  • SSH config file has keys specified for GitHub and GitLab:

    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

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
  • Initialize git in a directory:

    git init

  • Connect git to one remote repository (located in GitHub)

    git remote add origin [email protected]:your-username/your-repo.git

  • Rename .git to something like .github

    mv .git .github

  • Initialize git again

    git init

  • Connect git to the other remote repository (located in GitLab)

    git remote add origin [email protected]:your-username/your-repo.git

  • Rename .git to something like .gitlab

    mv .git .gitlab

  • Verify that current directory is connected to two different remote repositories

    git --git-dir=.github remote -v

    git --git-dir=.gitlab remote -v

  • Pull remote (GitHub and GitLab) repositories

    git --git-dir=.github pull origin main
    git --git-dir=.gitlab pull origin main
  • Add a file to both repositories

    git --git-dir=.github add README.md
    git --git-dir=.gitlab add README.md
  • Write commit message

    git --git-dir=.github commit -m "operational overview"
    git --git-dir=.gitlab commit -m "operational overview"
  • Push to remote

    git --git-dir=.github push -u origin main
    git --git-dir=.gitlab push -u origin main

The only additional thing we're doing here is using the --git-dir flag.

If you plan on doing this frequently you could add an alias in your shell config file (like .zprofile, bashrc, etc.):

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

Future operations like pull, push, add, commit can be performed like - github pull origin main , gitlab pull origin main, etc.