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

sshkey=$(git config ssh.key)

if [ -z "$sshkey" ]; then
  git_opt="-i ${sshkey}"
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/
cd ~/project-2
git config ssh.key $HOME/.ssh/

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

git config

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/ 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/'
git config --global 'clone -c ssh.key=~/.ssh/'

So then you only have to type:

git cp git://
git cw git://