Tired of accidentally committing to work repos with your personal email? Here’s how to automatically use the right Git profile based on where your repositories live.
1. Generate SSH Keys
Create separate keys for each account:
# Work key
ssh-keygen -t ed25519 -C "work@company.com" -f ~/.ssh/id_ed25519_work
# Personal key
ssh-keygen -t ed25519 -C "personal@gmail.com" -f ~/.ssh/id_ed25519_personal
2. Configure SSH Hosts
Edit ~/.ssh/config
:
# Work GitHub
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_work
IdentitiesOnly yes
# Personal GitHub (default)
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_personal
IdentitiesOnly yes
3. Set Up Git Profiles
Global config (~/.gitconfig
):
[user]
name = Your Name
email = personal@gmail.com
# Replace with your actual work directory path
[includeIf "gitdir:~/Documents/work/"]
path = ~/.gitconfig-work
[includeIf "hasconfig:remote.*.url:https://github.com/your-org/**"]
path = ~/.gitconfig-work
Work config (~/.gitconfig-work
):
[user]
name = Your Name
email = work@company.com
[url "git@github-work:your-org/"]
insteadOf = https://github.com/your-org/
insteadOf = git@github.com:your-org/
4. Add Keys to GitHub
Copy and add the public keys to their respective GitHub accounts:
cat ~/.ssh/id_ed25519_work.pub # Add to work GitHub
cat ~/.ssh/id_ed25519_personal.pub # Add to personal GitHub
5. Update Your Directory Structure
If your work repos are already scattered, move them to a dedicated directory:
# Create work directory
mkdir -p ~/Documents/work
# Move existing work repos (replace with your paths)
mv ~/existing-work-repo ~/Documents/work/
mv ~/another-work-project ~/Documents/work/
Or update the gitdir
path in step 3 to match where your work repos currently live.
6. Verify Your Setup
Test that the right profile activates in each location:
# Test SSH keys
ssh -T github-work # Should authenticate with work account
ssh -T github.com # Should authenticate with personal account
# Test Git profiles
cd ~/Documents/work/some-repo
git config user.email # Should show: work@company.com
cd ~/personal/some-repo
git config user.email # Should show: personal@gmail.com
Done!
Now Git automatically uses the correct profile and SSH key based on:
- Directory location (
~/work/
uses work profile) - Repository URL (your organization’s repos use work profile)
Test with ssh -T github-work
and ssh -T github.com
to verify both keys work.