EmilianoDecember 28, 2024

Managing Multiple GitHub Accounts Using SSH

In this post, we will explore how to configure multiple GitHub accounts on the same local machine using SSH, which is useful when we work on both personal and work projects.

The idea is to use different SSH keys for each account without having to enter credentials constantly.

Generate SSH keys for each GitHub account

When we work with multiple accounts, each account should have its own SSH key. We can generate a new SSH key for the second GitHub account using the following command:

ssh-keygen -t ed25519 -C "Key for my second account"

We should choose a distinctive file name, such as id_ed25519_second_account, to avoid overwriting the existing SSH key.

Add the SSH key to GitHub

Now we need to add the generated public key to our GitHub account. First, copy the public key content:

cat ~/.ssh/id_ed25519_second_account.pub

Then go to GitHub and in the Settings > SSH and GPG keys section, select New SSH Key and paste the content.

Configure the ~/.ssh/config file

The ~/.ssh/config file allows you to manage different keys for different hosts. Edit the file:

nano ~/.ssh/config

Add the following configurations:

# Personal account (default account)
Host github.com
        HostName github.com
        User git
        IdentityFile ~/.ssh/id_ed25519

# Secondary account (work or other projects)
Host github-testing
        HostName github.com
        User git
        IdentityFile ~/.ssh/id_ed25519_second_account

Configure repository remote URLs

For repositories that belong to our second account, we need to update the remote URL to use the configured alias:

git remote set-url origin git@github-testing:username/repository.git

Verify SSH configuration

Verify that GitHub recognizes you correctly:

For our personal account:

ssh -T git@github.com

For our second account:

ssh -T git@github-testing

If everything is correct, you will see a welcome message confirming successful authentication.

Push or pull with the correct account

Once configured, you can run push or pull normally. Git will automatically use the correct key associated with the repository alias.