How to use multiple SSH keys with Git

For the longest time I wanted to use multiple SSH keys. One for work and one for private use. The magic keyword is GIT_SSH. When this environment variable is set, Git will executes the program that the variable points to: Add this to your .bashrc file:

export GIT_SSH=$HOME/bin/gitssh

Create gitssh in your ~/bin directory

#!/bin/sh
sshkey=$(git config ssh.key)

if [ -z "$sshkey" ]; then
  git_opt=""
else
  git_opt="-i ${sshkey}"
fi
exec ssh $git_opt "$@"

When this is in place you can add your different SSH keys to your projects like:

cd ~/project-1
git config ssh.key $HOME/.ssh/project-1_key.pub
cd ~/project-2
git config ssh.key $HOME/.ssh/project-2_key.pub

You also might want to have different email addresses for the repositories. The best way is to set the user.email config setting in your repositories like:

git config user.name foo.bar@example.com

One last note, if you add the above you need to add ssh.key to all your repositories. So what do you do if you need to clone a new repository? You do not have any repository to get ssh.key. The solution is to add it when you clone.

git clone -c ssh.key=~/.ssh/id_rsa_work.pub git://git.foo.bar/proj.git

And if you are lazy like me you can create aliases out of this:

git config --global alias.cp 'clone -c ssh.key=~/.ssh/id_rsa.pub'
git config --global alias.cw 'clone -c ssh.key=~/.ssh/id_rsa_work.pub'

So then you only have to type:

git cp git://git.foo.bar/proj1.git
git cw git://git.foo.bar/proj2.git

Category: