Add multiple SSH keys with Github config
After 13 August 2021, git is not supporting HTTPs authentication method, so I believe this answer needs to be updated.
Follow the steps below:
- remove all SSH keys (public & private) for Git stored in directory
~/.ssh/
.
- create new SSH keys:
ssh-keygen -t rsa -b 4096 -C "[email protected]"
ssh-keygen -t rsa -b 4096 -C "[email protected]"
When asked for file names, give default ~/.ssh/id_rsa
for account1 and ~/.ssh/id_rsa_acc2
for account2 respectively.
- Start ssh-agent and add private keys for account1 and account2:
eval `ssh-agent`
ssh-add -k ~/.ssh/id_rsa
ssh-add -k ~/.ssh/id_rsa_acc2
confirm keys are added by command ssh-add -l
copy public keys for account1 and account2 and add it to your github account. command: cat ~/.ssh/id_rsa.pub | pbcopy
(to check whether its copied: pbpaste
set account1's username and user email as global GitHub config:
git config --global user.name "acc1_username"
git config --global user.email "[email protected]"
- create
~/.ssh/config
file with following configuration:
# account1 github
Host github.com
HostName github.com
User git
AddKeysToAgent yes
IdentityFile ~/.ssh/id_rsa
# account2 github
Host github.com-acc2
HostName github.com
User git
AddKeysToAgent yes
IdentityFile ~/.ssh/id_rsa_acc2
- To set GitHub account2 for a project set username & email on project level in the project root directory:
git config user.name "acc2_username"
git config user.email "[email protected]"
- Now clone or add origin by using SSH link of GitHub repo:
# for account1 repo
git remote set-url origin [email protected]:acc1_username/reponame.git
# for account2 repo
git clone [email protected]:acc2_username/reponame.git
Feel free to add comments for any doubts.