1. Generate SSH keys with different names
ssh-keygen -t rsa -C "my_email@domain.com"
Keep them with different names. Lets say I created mine having path as followings -
~/.ssh/id_rsa_github
~/.ssh/id_rsa_gitlab
Optional - You may need to add generated key to local ssh-agent using
ssh-add <path of id_rsa key>
Running ssh-add -l
would provide you list of saved SSH keys. Optional - Use ssh-add -D
to clear any caches.
2. Create the SSH config
Navigate to .ssh
folder present in main user accout folder and create a config
file.
cd ~/.ssh/
touch config
Edit the config
file to put following contents into it.
# GitHub account
Host github.com
HostName github.com
# User MyGitHubUserName <- This is optional
IdentityFile ~/.ssh/id_rsa_github
# GitLab account
Host gitlab.domain.com
HostName gitlab.domain.com
# User MyGitLabUserName <- This is optional
IdentityFile ~/.ssh/id_rsa_gitlab
# ### MULTIPLE SSH IDENTITY FILES FOR THE SAME DOMAIN ###
# GitHub personal account
Host github-personal # keep the remote URL as "git@github-personal:[full-repo-path]" instead of "git@github.com:[full-repo-path]"
HostName github.com
# GitHub work account
Host github-work # keep the "-work" in remote URL like "git@github-work:[full-repo-path]"
HostName github.com
3. Set local or global user details in .gitconfig
If you have same User_Name and Email, then you can user the global .gitconfig
to store commiter's detail.
git config --global user.email "my_email@domain.com" // same as SSH keys
git config --global user.name "<My Name> OR MyName"
Or else, you need to set local user details in each repo's clone separately specific to that repo.
git config user.email "my_email@domain.com" // same as SSH keys
git config user.name "<My Name> OR MyName"
4. Test configurations
Use git's pull
, commit
and push
commands to test newly added configurations. This works with both HTTPS and SSH urls. But, it works better with SSH and doesn't require UserName and Email everytime.