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
| |
Add your SSH private key to the ssh-agent:
Add the Key to GitHub Account
# Adding a new SSH key to your GitHub account
Copy the public key:
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:
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:
| |
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:
| |
Test Connection
Verify the configuration is easy. Test the connection by the following command (notice that the ssh username is git):
| |
If success, the corresponding GitHub username (aka x1, x2) will be displayed after “Hi”.