Setup multiple git ssh accounts for git
- Generate SSH keys
ssh-keygen -q -t rsa -C "john.smith@github.com" -f ~/.ssh/id_rsa -N ""
ssh-keygen -q -t rsa -C "john.smith@company.com" -f ~/.ssh/id_rsa_pro -N ""
- Link them with GitHub/Bitbucket, or any other account
- Use following example to set each ssh key for every repository in your
~/.ssh/config
file You can configure ssh to send a use of a specific encryption key depending on the host. By this configuration, we can achieve of having multiple aliases for the same hostname.
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
IdentitiesOnly=yes
Host gitlab.com
Hostname gitlab.com
User git
IdentityFile ~/.ssh/id_rsa_pro
IdentitiesOnly=yes
- Git remote configuration
We can use these aliases in the git remotes by changing
git@github.com
togit@github_pro
.
Another option is to change existing projects remotes to something like git remote set-url origin git@github_pro:foo/bar.git
or adapt them directly during cloning
git clone git@github.com:johnsmith/example.git
git clone git@github_pro:johnsmith/example.git
Set multiple git identities
- In your home directory create separate directories for your private and work repositories
$ mkdir private && mkdir work
# Used for personal repositories
$ ls private
# Used for work repositories
$ ls work
- Remove the [user] block in your
~/.gitconfig
file and add the following
[includeIf "gitdir:~/private/"]
path = .gitconfig-private
[includeIf "gitdir:~/work/"]
path = .gitconfig-work
- In
~/.gitconfig-private
add your personal user information
[user]
email = john.smith@github.com
name = John Smith
- In
~/.gitconfig-work
add your work user information
[user]
email = john.smith@company.com
name = John Smith
Test setup
Note: includeIf works only in repositories under ~/private/
or ~/work/
and not in a non-repo directory.
Check if your settings were taken into account for instance in ~/private/<repository>
$ cd ~/private/<repository>
$ git config --get user.name
$ git config --get user.email
You can also display and check the global git config
$ git config --list --global
Or just the local config for the repository folder you are in
$ git config --list