This approach allows you to use different ssh keys with multiple github accounts only with git config, and without any intrusive changes in repos / urls.
This approach allows for routing of SSH keys based on URL regex in the global gitconfig (no SSH config required).
From what I can see min requirements are Git 2.36+ as it introduced hasconfig support.
This solution has a different approach to other options available, including:
- Different ssh hosts (e.g. git clone [email protected]:...)
- Different folder paths (i.e. using gitdir from path)
- Manual git config local overrides of
sshCommandto point to different keys - Scripts / extra tools to switch accounts (e.g. which basically override one of the above)
All solutions have pros and cons; in my case the least intrusive approach is the URL regex routing provided below.
Create a config file that will be imported specifically for relevant repos.
Here you need to point to the respective SSH key for these seleted repos.
~/.gitconfig-work:
[core]
sshCommand = ssh -i ~/.ssh/id_rsa-work -o IdentitiesOnly=yes # YOUR SSH KEY HERE
[user]
name = Your Name
email = [email protected]Now you can define a) a default ssh key for "all the rest", and b) the specific url paths to apply the custom path for.
~/.gitconfig:
# Default personal settings
[user]
name = Your Name
email = [email protected]
# This points to the default ssh key
[core]
sshCommand = ssh -i ~/.ssh/id_rsa -o IdentitiesOnly=yes # YOUR DEFAULT SSH PATH HERE
# Auto-detect work organizations
[includeIf "hasconfig:remote.*.url:*github.com:companyname**/*"]
path = ~/.gitconfig-work
[includeIf "hasconfig:remote.*.url:*github.com*work-username*"]
path = ~/.gitconfig-workImportant: Remove or comment out any IdentityFile entries for github.com in ~/.ssh/config:
# REMOVE or comment these out:
# Host github.com
# IdentityFile ~/.ssh/id_rsa
Once this is done, you can clone any repository normally - the correct SSH key is selected automatically:
# Uses personal key automatically
git clone [email protected]:personal-user/repo.git
# Uses work key automatically
git clone [email protected]:company-org/repo.git- Git scans remote URLs when loading config
- If URL matches work patterns it includes work config
- Work config overrides SSH key via
core.sshCommand - SSH config conflicts are avoided by removing competing entries
Simply add more includeIf patterns:
[includeIf "hasconfig:remote.*.url:*github.com*another-org*"]
path = ~/.gitconfig-work