If you want to be able to work on different repositories with different GitHub accounts, for example using a work account for one repository and a home account for another repository, then this is what you need to do. In summary:
- Generate an SSH key on the local machine for each account you want to use
- Edit the /.ssh config file to include Host information for each account
- For individual repos, change the remote url to specify the Host to use
Generate an SSH key on the local machine for each account you want to use
When you do the following, fight the tendency to accept default options. We'll need to make sure not to accept the default name for a new SSH key and instead save it under a custom name.
For any GitHub account you don't have a local SSH key for yet, run ssh-keygen -t rsa -C "email@address.here"
for the email address associated with that GitHub account.
When it generates the key, save it under a new name, so instead of the default id_rsa make it, for example, id_rsa_HOME or id_rsa_WORK.
Your current keys are located in the .ssh folder. You can view existing pub keys by running ls ~/.ssh/*.pub
Edit the /.ssh config file to include Host information for each account
Edit the SSH config in ~/.ssh/config
and add any additional GitHub accounts on top of the default account. You need a unique Host for each, for example github.com-username, and add the SSH key you created for it.
Example config:
#HOME
Host github.com-homeuser
HostName github.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
AddKeysToAgent yes
#WORK
Host github.com-workuser
HostName github.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_WORK
AddKeysToAgent yes
For individual repos, change the remote url to specify the Host to use
If you have a default GitHub account you use, but have a specific repository you want to use a different GitHub account for, check the current Host by running git remote -v.
The remote will be something like:
origin git@github.com:username/repo.git (fetch)
origin git@github.com:username/repo.git (push)
We want to change this to something like:
origin git@github.com-workuser:username/repo.git (fetch)
origin git@github.com-workuser:username/repo.git (push)
To do so, simply run git remote set-url origin git@github.com-workuser:username/repo.git
Now this repository will use your work user account and its SSH key.