For osx
Create different ssh key according the article: Generate new SSH key
$ ssh-keygen -t ed25519 -C "my_email@provider.com"
for example, 2 keys created at:
~/.ssh/id_rsa
~/.ssh/id_other-account
then, add these two keys as following
$ ssh-add -K ~/.ssh/id_rsa
$ ssh-add -K ~/.ssh/id_other-account
-K saves it to the keychain
You can delete ALL cached keys with
$ ssh-add -D
You can check saved keys with
$ ssh-add -l
$ vim ~/.ssh/config
Then add:
# Main account
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
IdentitiesOnly yes
# Other account
Host github.com-other-account
HostName github.com
User git
IdentityFile ~/.ssh/id_other-account
IdentitiesOnly yes
Host *
AddKeysToAgent yes
UseKeychain yes
The last bit is only needed if you supplied
-Kwith ssh-add.
So you won't have to re-type your password after restart computer
Of course you can use a single key for other git providers as well, like gitlab or bitbucket.
When cloning a repo, provide the host of the account you want to use
$ git clone git@github.com-other-account:<username>/<repo>.git targetdir
If you need to update an existing repo, you can update the targetdir/.git/config file by typing
$ git remote set-url origin git@<host-in-ssh-config>:<username>/<repo>
Or manually edit the config file
If you use your "other-account" only for one organization, say "acme-org" you can supply the line below so that it is automatically used when cloning.
git config --global url."git@github.com-other-account:acme-org/".insteadOf "git@github.com:acme-org/"
This is not required for access, but used in commits.
You can set this globally for your main account and locally for your "other-account".
Set globally for your main account:
$ git config --global user.name "Jorn"
$ git config --global user.email "my_email@provider.com"
Set in project for the other account:
$ git config user.name "Jorn"
$ git config user.email "my_email@some-project.com"
If there are multiple repo's connected to the other account this becomes tedious.
You can extend the global config by a directory match pattern:
~/.gitconfig
[user]
name = Jorn
email = my_email@provider.com
# note the trailing /
[includeIf "gitdir:~/workdir/"]
path = ~/workdir/.gitconfig
~/workdir/.gitconfig
[user]
email = my_email@some-project.com
This will enable the alternate email address for ~/workdir/ recursively.
Ready, set, go!
Credits:
- https://gist.github.com/jexchan/2351996
- https://www.freecodecamp.org/news/how-to-manage-multiple-ssh-keys/
- https://stackoverflow.com/questions/4220416/can-i-specify-multiple-users-for-myself-in-gitconfig/43654115#43654115
- https://docs.github.com/en/account-and-profile/how-tos/account-management/managing-multiple-accounts#contributing-to-multiple-accounts-using-ssh-and-multiple-keys
Note that
[includeIf "gitdir:~/workdir/"]should end with a/to catch all sub dirs.