Create different ssh keys according to the Github documentation
ssh-keygen -t rsa -C "your_email@youremail.com"
For example, 2 keys were created at
~/.ssh/personal-on-mac
~/.ssh/work-on-mac
Create/modify the ssh config file
vim ~/.ssh/config
Then add
# Personal account
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/personal-on-mac
# Work account
Host git.work.com
HostName git.work.com
User #####
IdentityFile ~/.ssh/work-on-mac
Start the ssh-agent
eval "$(ssh-agent -s)"
To be sure which domain (personal, work or...) you are working on, you can all the existing keys which are cached and add the corresponding private key to the OpenSSH authentication agent:
ssh-add -D
ssh-add ~/.ssh/work-on-mac
The bash functions can help you to switch between accounts smoothly
function personal-git() {
ssh-add -D
ssh-add ~/.ssh/personal-on-mac
echo "You are using your PERSONAL ssh key"
}
function work-git() {
ssh-add -D
ssh-add ~/.ssh/work-on-mac
echo "You are using your WORK key"
}
If you find it annoying to change your email in the .gitconfig
file each time you want to switch between personal and work git, you can use conditional git configuration based on where your repositories are located on your machine. Let's imagine all your work-related repositories are in ~/workspace/
then you can configure ~/.gitconfig
like following
// ~/.gitconfig
[user]
name = Jane doe
email = jane@doe.com
[includeIf "gitdir:~/workspace/"]
path = ~/workspace/.gitconfig
And in the ~/workspace/.gitconfig
put your work email so it overrides the default values
// ~/workspace/.gitconfig[user] email = jane@work.com