Anil K. Shrestha
Published on

Adding Multiple Git Accounts

Managing multiple Git accounts on a single machine can be essential for developers juggling personal and work projects. This guide will help you set up multiple Git accounts efficiently.

Generate SSH Keys

First, generate SSH keys if you haven't already:

ssh-keygen -t rsa -b 4096 -C "<email address 1>"
ssh-keygen -t rsa -b 4096 -C "<email address 2>"

Ensure you use different filenames for each key, e.g., id_rsa_personal and id_rsa_work.

Then, copy the SSH keys to the respective GitHub/GitLab accounts:

cat ~/.ssh/<id file name>.pub
# Example: cat ~/.ssh/id_rsa_personal.pub

Configure SSH

Create a configuration file for SSH:

vim ~/.ssh/config

Add the following configuration:

Host <host_name1>
    HostName github.com
    User git
    IdentityFile ~/.ssh/<id file name 1>
Host <host_name2>
    HostName github.com
    User git
    IdentityFile ~/.ssh/<id file name 2>

For example, to configure GitHub and GitLab:

Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_personal
Host gitlab.com
    HostName gitlab.com
    User git
    IdentityFile ~/.ssh/id_rsa_work

Update Git Configuration

Edit your global Git configuration file:

vim ~/.gitconfig

Add the default user configuration:

[user]
    name = <default user>
    email = <default email>
[includeIf "gitdir:~/<work folder>/"]
    path = ~/<work folder>/.gitconfig

This tells Git to use the default user unless within the specified work folder.

Next, create a specific configuration for your work folder:

vim ~/<work folder>/.gitconfig

Add your work user configuration:

[user]
    name = <work user>
    email = <work email>

Add SSH Keys to SSH Agent

Add the generated SSH keys to the SSH agent:

ssh-add ~/.ssh/id_rsa_personal
ssh-add ~/.ssh/id_rsa_work

Test Configuration

Finally, test the SSH connections to ensure everything is set up correctly:

ssh -T github.com
ssh -T gitlab.com

You should now be able to seamlessly switch between your personal and work Git accounts based on the folders you are working in.