Confgure Multiple Github Accounts On One Machine
How to use different github account for different repository? For
instance, we have two github accounts x1 and
x2, while x1 for repo1 and
x2 for repo2. At the first glance, we can set
git config in different repository folder by
git config user.name xxx. However, this approach has two
drawbacks:
- Need to config user name/email in every repository
- In some case, the git user cannot be configured by
git config. For example, hexo-deployer-git. Since the git repo is automatically generated by the deployer, it's hard to manually set the user name.
Fortunately, we can leverage SSH config to associate different github accounts with different repos. Define different host entries does the trick: since we login to github via SSH, we use a virtual host as an alias to represent the real host name.
Generating a New SSH Key
# Generating a new SSH key and adding it to the ssh-agent
1 | ssh-keygen -t ed25519 -C "your_email@example.com" |
Add your SSH private key to the ssh-agent: 1
2ssh-add ~/.ssh/id_ed25519
Identity added: /home/user/.ssh/id_ed25519 (your_email@example.com)
Add the Key to GitHub Account
# Adding a new SSH key to your GitHub account
Copy the public key:
1 | cat ~/.ssh/id_ed25519.pub |
Add the key to github account in github main page: Profile Photo -> Settings -> SSH and GPG keys -> New SSH keys
Edit SSH Config
This is the most important part, create or edit
~/.ssh/config: 1
2
3
4
5
6
7
8
9
10
11
12
13
14Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
Host githubx1
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_x1
Host githubx2
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_x2
Explanations for the config file:
- Host: the host alias as well as the section name
- HostName: the real host name to login
- User: the username for the SSH connection
- IdentityFile : the SSH private key file generated before
For the above sample config file, assume the key file/github account mapping is:
id_rsa->main@example.comid_rsa_x1->x1@example.comid_rsa_x2->x2@example.com
Typically, a repo's remote url looks like this:
1 | git@github.com:finisky/TextCNN.git |
By default, we will access the repo by identity
main@example.com because the repo remote host is
github.com. If we want to access the repo by
x1@example.com, just change the remote url to:
1 | git@githubx1:finisky/TextCNN.git |
Test Connection
Verify the configuration is easy. Test the connection by the
following command (notice that the ssh username is
git):
1 | ssh -T git@githubx1 |
If success, the corresponding GitHub username (aka x1,
x2) will be displayed after "Hi".