Git: Multiple accounts with Bitbucket
Create a unique SSH keypair for each of your accounts and upload the various keys to each of those accounts via the Bitbucket account settings.
Create a file called "config" in the root of your .ssh directory.
In the config file, create a listing for each account you need to manage:
host bitbucket.org:my_user_name
HostName bitbucket.org
User my_user_name
IdentityFile ~/.ssh/path_to_my/private_key
host bitbucket.org:my_other_user_name
HostName bitbucket.org
User my_other_user_name
IdentityFile ~/.ssh/path_to_my/other_private_key
Since these keys have unique names (unlike the default "id_rsa" name) these keys will not be loaded into SSH unless you explicitly request it. You don't want to have to do this every time you open a terminal.
- Open your bash config file. It is probably called ".bashrc" and may exist in the same directory as your ".ssh" directory.
Add the following script, adjusting the private key names to reflect the same names you used above:
#! /bin/bash
eval `ssh-agent -s`
ssh-add ~/.ssh/path_to_my/private_key
ssh-add ~/.ssh/path_to_my/other_private_key
Now whenever you open the terminal you should be prompted for the passwords for each key you added. Once you put in those passwords, you should be all set to push to/pull from any repo connected to those bitbucket accounts.
- But there is one last thing you have to remember. Normally you might add the bitbucket remote repo like this:
git remote add origin git@bitbucket.org:myusername/my_project.git
To make use of your config file you need to add those remotes like this;
git remote add origin ssh://git@bitbucket.org:myusername/MyUserName/my_project.git
Notice the "ssh://" prepended to the URL. Also notice the addition of "MyUserName" as a sort of subdirectory. When communicating over SSH, that subdirectory path is used by bitbucket to acknowledge you as that user and then your SSH config will serve up the key associated with that user.
Written by Matt
Related protips
1 Response
Very helpful, thanks! Works for me on OS X, though I put my ssh-add commands into ~/.bash_profile.