So, if you're like me and use the same machine for both work and personal projects, you've probably run into the challenge of managing multiple GitHub accounts. Switching between two Git accounts - one for work and one for personal use - can be tricky, especially when you need to ensure the right credentials are used for each repository. In this guide, I'll walk you through how to set up your machine to easily switch between Git accounts without the hassle.
You might have a SSH key and added it to remote git account (GitHub, Bitbucket etc) already for work. If so, you can skip this step for work account and only do for personal.
You can create more, if you want to configure more accounts
ssh-keygen -t rsa -C "[email protected]" -f ~/.ssh/id_rsa_personalGo to your respective GitHub or Bitbucket account settings and add the corresponding SSH public key ~/.ssh/id_personal.pub in the account and so on if more.
Add these keys to your SSH configuration to tell Git which key to use for each account. Edit the ~/.ssh/config file:
Host github.com-work
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
IdentitiesOnly yes
AddKeysToAgent yes
Host github.com-personal
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_personal
IdentitiesOnly yes
AddKeysToAgent yesNow, create Git aliases for each account. This way, you can easily switch between profiles with a single command. Add the following to your .zshrc / .bashrc based on your shell:
git_use_personal() {
git config user.name "user name personal"
git config user.email "[email protected]"
old_url=$(git remote get-url origin)
clean_url=$(echo "$old_url" | sed -E 's/github\.com(-work|-personal)?/github.com/')
new_url=$(echo "$clean_url" | sed 's/github.com/github.com-personal/')
git remote set-url origin "$new_url"
export GIT_SSH_COMMAND='ssh -i ~/.ssh/id_rsa_personal'
echo "✅ Switched to PERSONAL Git profile"
}
git_use_work() {
git config user.name "user name work"
git config user.email "[email protected]"
old_url=$(git remote get-url origin)
clean_url=$(echo "$old_url" | sed -E 's/github\.com(-work|-personal)?/github.com/')
new_url=$(echo "$clean_url" | sed 's/github.com/github.com-work/')
git remote set-url origin "$new_url"
export GIT_SSH_COMMAND='ssh -i ~/.ssh/id_rsa'
echo "✅ Switched to WORK Git profile"
}Voilà! Now you can easily switch between accounts:
git_use_personal # For your personal account
git_use_work # For your work accounteval $(ssh-agent -s)ssh-add ~/.ssh/id_rsa_personalssh -T [email protected]ssh-add -lHappy coding with multiple Git accounts! 🚀