Managing multiple Git accounts on the same machine can be simplified with the following steps. This guide ensures you can seamlessly work with personal and work accounts.
Generate separate SSH key pairs for each GitHub account:
cd ~/.ssh
ssh-keygen -t rsa -C "your_email_for_personal_account@example.com" -f "github-personal"
ssh-keygen -t rsa -C "your_email_for_work_account@example.com" -f "github-work"
-f flag specifies the filenames for the key pairs.Add the generated keys to your SSH agent:
ssh-add --apple-use-keychain ~/.ssh/github-personal
ssh-add --apple-use-keychain ~/.ssh/github-work
For Linux or non-Mac environments:
ssh-add ~/.ssh/github-personal
ssh-add ~/.ssh/github-work
Copy each public key and add them to the corresponding GitHub accounts.
pbcopy < ~/.ssh/github-personal.pub # Mac
cat ~/.ssh/github-personal.pub | xclip -selection clipboard # Linux
Repeat for the second account:
pbcopy < ~/.ssh/github-work.pub
Edit the SSH config file to define separate host entries for each account:
open -e ~/.ssh/config # Mac
nano ~/.ssh/config # Linux
Add the following configuration:
# Personal account
Host github-personal
HostName github.com
User git
IdentityFile ~/.ssh/github-personal
# Work account
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/github-work
Set your global Git username and email for the default (personal) account:
git config --global user.name "Your Personal Name"
git config --global user.email "your_email_for_personal_account@example.com"
For repositories requiring your work account, override the default configuration:
cd /path/to/your/repository
git config user.name "Your Work Name"
git config user.email "your_email_for_work_account@example.com"
Use the host alias defined in the SSH config:
For personal account:
git clone git@github-personal:username/repo.git
For work account:
git clone git@github-work:username/repo.git
To switch the account used by an existing repository:
git remote set-url origin git@github-work:username/repo.git
Verify the SSH setup for each account:
ssh -T github-personal
ssh -T github-work
You should see a welcome message for each respective GitHub account.
Check which account is in use for a repository:
git config user.name
git config user.email
Update them as necessary:
git config user.name "Your Work Name"
git config user.email "your_email_for_work_account@example.com"