Table of Contents
1. Context
Do you use two or more GitHub accounts – one for official use, another for personal use, and so on? Did you encounter issues like Git commands are using the wrong SSH key or the wrong GitHub user id or you can use repositories from one GitHub account but not from others? If yes, then read on.
In this article, we are assuming you have two GitHub accounts account1
and account2
setup using emails Ids [email protected]
and [email protected]
respectively.
2. Generate and Configure SSH Keys
For each of your GitHub accounts, generate SSH keys using the corresponding email Ids and add the public key to GitHub.
# Generate keys for the first account. Default file name is id_rsa, change it to github_account1_id_rsa # It creates two files: ~/.ssh/github_account1_id_rsa and ~/.ssh/github_account1_id_rsa.pub ssh-keygen -t rsa -b 4096 -C "[email protected]" # Generate keys for the second account. Default file name is id_rsa, change it to github_account2_id_rsa # It creates two files: ~/.ssh/github_account2_id_rsa and ~/.ssh/github_account2_id_rsa.pub ssh-keygen -t rsa -b 4096 -C "[email protected]"
Copy the above generated public key (the content of .pub
file) and add it to the corresponding GitHub account at Settings > SSH and GPG Keys > Add New
in https://github.com/settings/ssh/new
3. Create Aliases and Configure
Create two different aliases of GitHub hosts with the appropriate identity file in ~/.ssh/config
# Alias for the first GitHub account Host github.com-account1 HostName github.com User git IdentityFile ~/.ssh/github_account1_id_rsa IdentitiesOnly yes # Alias for the second GitHub account Host github.com-account2 HostName github.com User git IdentityFile ~/.ssh/github_account2_id_rsa IdentitiesOnly yes
Now, change the remote URL of the local Git repo in <repo_path>/.git/config
# In first repo from first account [remote "origin"] url = [email protected]:userid1/repo1.git fetch = +refs/heads/*:refs/remotes/origin/* # In second repo from second account [remote "origin"] url = [email protected]:userid2/repo2.git fetch = +refs/heads/*:refs/remotes/origin/*
4. Troubleshooting
If you encounter issues, enable verbose mode to troubleshoot. All subsequent Git commands will produce SSH logs that will help you understand and fix the issue.
# Enable verbose in the repo git config core.sshCommand "ssh -vvv" # Disable verbose in the repo git config core.sshCommand "ssh"
5. Conclusion
You are all set to use multiple GitHub accounts from your machine. This approach is applicable when you are using multiple accounts in GitLab, BitBucket, etc. as well.
Join our list to get instant access to new articles and weekly newsletter.