Use Multiple Git Accounts in Sinlge Syetm
Lets say we have two accounts.
- account01
- account02
1. Open Terminal and run:
# GitHub (account01)
ssh-keygen -t ed25519 -C "account01-github" -f ~/.ssh/id_github_account01
# GitHub (account02)
ssh-keygen -t ed25519 -C "account02-github" -f ~/.ssh/id_github_account02
# GitLab (account01)
ssh-keygen -t ed25519 -C "account01-gitlab" -f ~/.ssh/id_gitlab_account01
# GitLab (account02)
ssh-keygen -t ed25519 -C "account02-gitlab" -f ~/.ssh/id_gitlab_account02
3. Start SSH Agent
eval "$(ssh-agent -s)"
4. Create and modify: ~/.ssh/config:
touch ~/.ssh/config
nano ~/.ssh/config
Add this configuration:
# GitHub (account01)
Host github.com-account01
HostName github.com
User git
IdentityFile ~/.ssh/id_github_account01
IdentitiesOnly yes
# GitHub (account02)
Host github.com-account02
HostName github.com
User git
IdentityFile ~/.ssh/id_github_account02
IdentitiesOnly yes
# GitLab (account01)
Host gitlab.com-account01
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_gitlab_account01
IdentitiesOnly yes
# GitLab (account02)
Host gitlab.com-account02
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_gitlab_account02
IdentitiesOnly yes
5. Add keys to keychain:
# GitHub (account01)
ssh-add --apple-use-keychain ~/.ssh/id_github_account01
# GitHub (account02)
ssh-add --apple-use-keychain ~/.ssh/id_github_account02
# GitLab (account01)
ssh-add --apple-use-keychain ~/.ssh/id_gitlab_account01
# GitLab (account02)
ssh-add --apple-use-keychain ~/.ssh/id_gitlab_account02
# Verify all the kys are added
ssh-add -l
- Copy public keys (one at a time):
# Copy GitHub key, then paste in GitHub Settings > SSH Keys
# GitHub (account01)
pbcopy < ~/.ssh/id_github_account01.pub
# GitHub (account02)
pbcopy < ~/.ssh/id_github_account02.pub
# Copy GitLab key, then paste in GitLab Settings > SSH Keys
# GitLab (account01)
pbcopy < ~/.ssh/id_gitlab_account01.pub
# GitLab (account02)
pbcopy < ~/.ssh/id_gitlab_account02.pub
7. Test the connection:
# GitHub (account01)
ssh -T git@github.com-account01
# GitHub (account02)
ssh -T git@github.com-account02
# GitLab (account01)
ssh -T git@gitlab.com-account01
# GitLab (account02)
ssh -T git@gitlab.com-account02
8. Use the SSH for account01
# for new project
git clone git@github.com-account01:git-username/repository.git
# for existing project
git remote set-url origin git@github.com-account01:git-username/repository.git
Note:
Git’s default url with orging is git@github.com:git-username/repository.git
And we have to modify the orgin from git@github.com to git@github.com-account01
Usefull tip:
git remote -vget current remote url