Using Multiple Git Accounts with SSH

Multiple Git accounts are easiest to manage with one key per identity and SSH host aliases. Do not keep swapping the global Git configuration and hoping muscle memory selects the correct employer.

1. Generate separate keys

Prefer Ed25519 unless a legacy server requires RSA:

1
2
ssh-keygen -t ed25519 -C "primary@example.com" -f ~/.ssh/github_primary
ssh-keygen -t ed25519 -C "secondary@example.com" -f ~/.ssh/github_secondary

Upload each .pub file to the matching Git provider account. Never upload or share the private-key file.

2. Add keys to the agent

1
2
3
4
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/github_primary
ssh-add ~/.ssh/github_secondary
ssh-add -l

ssh-agent is not a stack sent to the server. It is a local process that holds private keys and performs signing operations on behalf of SSH clients; the private key itself stays local.

3. Configure host aliases

1
2
3
4
5
6
7
8
9
10
11
12
# ~/.ssh/config
Host github-primary
HostName github.com
User git
IdentityFile ~/.ssh/github_primary
IdentitiesOnly yes

Host github-secondary
HostName github.com
User git
IdentityFile ~/.ssh/github_secondary
IdentitiesOnly yes

Protect the files:

1
2
chmod 700 ~/.ssh
chmod 600 ~/.ssh/config ~/.ssh/github_primary ~/.ssh/github_secondary

IdentitiesOnly yes prevents SSH from offering every loaded key until the server gets bored and rejects the connection.

4. Use the alias in Git remotes

1
git remote add origin git@github-primary:primary-user/project.git

Test each identity:

1
2
ssh -T git@github-primary
ssh -T git@github-secondary

Also set repository-local commit identity when needed:

1
2
git config user.name "Hudson"
git config user.email "primary@example.com"

SSH selects the account used to authenticate. Git’s user.name and user.email select the author written into commits. They are related, but they are not the same switch.