Using multiple accounts with remote repositories can be a SSH key hell. In this post I'll explain how you can make Git select the correct SSH key for the project you are currently working on.
Create a key for each of your accounts
To generate a new key pair simply run this command in the ~/.ssh/ folder:
ssh-keygen -t rsa -C "user1" -f "user1"
The -C option is a comment to help identify the key. The -f option specifies the file name.
Repeat the above for each Bitbucket account you want to use.
Add the public key to the correct Bitbucket account
To add a public key to a Bitbucket account, you need to go to the Bitbucket Settings Screen. Select SSH Keys in the left side menu and click Add key.
For more detailed information check out the Bitbucket documentation:
In ~/.ssh/ create a file called config with contents based on this:
#user1 account Host bitbucket.com-user1 HostName bitbucket.com User git IdentityFile ~/.ssh/user1 IdentitiesOnly yes #user2 account Host bitbucket.com-user2 HostName bitbucket.com User git IdentityFile ~/.ssh/user2 IdentitiesOnly yes
Replace user1 or user2 with your Bitbucket usernames
Getting your keys on a keyring
This is only useful if you use a passphrase to protect your key. Otherwise you can skip this.
Depending on your operating system you’ll need to find out how best to do this.
Linux users can use GnomeKeyring.
Mac users can use the following command to permanently add keys to the Mac SSH Agent:
ssh-add -K ~/.ssh/user1.rsa
Windows users can take a look here for more info: Git On Windows
You can check the keys on your keyring with:
Configure your Git repo
If you don't have a local copy of your repo, you have to run the following command to clone a Bitbucket repository:
git clone email@example.com:user1/your-repo-name.git
If you already have a local copy, you'll need to update the origin:
git remote set-url origin firstname.lastname@example.org:user1/your-repo-name.git
Now go to the local Git repo that you want to configure and enter:
git config user.name "user1" git config user.email "email@example.com"
Where user1 matches the values you used earlier in your ssh config.
You can now git push as normal and the correct key will automatically be used.
This post is based on the following sources:
- Automatically use correct SSH key for remote Git repo by Tom Atkins
- http://unix.stackexchange.com/a/140077 by slm
- https://gist.github.com/jexchan/2351996#gistcomment-1623390 by Adam M Dutko