Recently, I needed to use different Github accounts to access different repos on my work computer. After encountering some issues, I finally managed to set it up, and now I can freely switch accounts to access different repos.
- Create SSH keys for each account: Generate a new SSH key and add it to the SSH agent
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/github_a
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/github_b
- Add the public keys (github_a.pub, github_b.pub) to their respective Github accounts: Go to Github > settings > SSH and GPG keys.
- Start the ssh-agent in the background.
$ eval "$(ssh-agent -s)"
- Add the private keys of the generated keys to the ssh-agent.
ssh-add ~/.ssh/github_a
ssh-add ~/.ssh/github_b
- Edit the ~/.ssh/config file.
vim ~/.ssh/config
Host gtihub_q
HostName github.com
AddKeysToAgent yes
User git
UseKeychain yes
IdentityFile ~/.ssh/github_a
Host github_b
HostName github.com
AddKeysToAgent yes
User git
UseKeychain yes
IdentityFile ~/.ssh/github_b
- Use the following commands to log in and clone the repository.
ssh -T git@github_a
git clone git@github_a:XXXXX/XXXXX.git
It is important to modify the default command given by the repository when cloning. Change git clone [email protected]:XXXXX/XXXXX.git
to git clone git@github_a:XXXXX/XXXXX.git
.
- If you have already cloned the repository, you need to modify the remote origin. Change the original source:
origin [email protected]:xxxxx/xxxxx.git (fetch)
origin [email protected]:xxxxx/xxxxx.git (push)
to:
origin git@github_a:xxxxx/xxxxx.git (fetch)
origin git@github_a:xxxxx/xxxxx.git (push)
This way, you can access different repos without constantly switching accounts.