tagged: Coding

Using Github and Bitbucket at the same time

If like me you’re in the midst of moving away from Bitbucket to Github or vice-versa, or if you have like having private repos at Bitbucket and your public at Github, then this may be of value. I am slowly transitioning over and making new repos on Github but in the meantime I still have a lot of active repos on Bitbucket, so I want the flexibility to talk to both — this guide will show you how.

Prerequisites

  • Git is set up for a single github user using https, not ssh
  • There is only a known_hosts file in ~/.ssh/
  • You already have an account at Github and another at Bitbucket

Talking to Bitbucket & Github

In this instance, Github will be the main account and Bitbucket the secondary; you can of course alternate this.

Create SSH key

In your commandline run the following (enter a passphrase when prompted):

ssh-keygen -t rsa -C "github email"

Save keys to: ~/.ssh/id_rsa

Repeat this step for Bitbucket; using the same email address is fine.

ssh-keygen -t rsa -C "bitbucket email"

Save Bitbucket key to: ~/.ssh/id_rsa_bb

Attaching the keys

Add your newly created keys to their respective accounts. You can use a simple command to copy each key:

pbcopy < ~/.ssh/id_rsa.pub
pbcopy < ~/.ssh/id_rsa_bb.pub

Windows users can use

cat ~/.ssh/id_rsa.pub | clip
cat ~/.ssh/id_rsa_bb.pub | clip

Create a config file

Create a config file in the root of your .shh/ folder. Inside should contain:

#Github (default)
  Host gh
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa

#Bitbucket (secondary)
  Host bb
  HostName bitbucket.org
  User git
  IdentityFile ~/.ssh/id_rsa_bb

Add the identities to SSH

Enter a passphrase when prompted after running the following commands.

ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_bb

You can check the keys were added, via ssh-add -l. Next I would suggest testing that the keys work with their remote accounts:

ssh -T gh
ssh -T bb

Using the new setup

Here an example of how we’d get going with a git repo:

mkdir ~/myproject && cd ~/myproject
touch readme.md
git init
git add .
git commit -am "first commit"
git remote add origin git@gh:username/myproject.git
git push origin master

The same would go for Bitbucket repos. The only thing you’d need to change is the remote.

Use case: Repo already exists on (bitbucket)

Let’s say you have a repo already working locally that works with Bitbucket &mdash well it won’t now. So let’s fix this. First of all, confirm you’re remote is wrong by running

git remote -v
# View current remotes
origin  https://bitbucket.org/username/myproject.git (fetch)
origin  https://bitbucket.org/username/myproject.git (push)

Now let’s remove our old remote and add the new one so that we can push and pull without any problems

git remote rm origin
# Remove remote
git remote -v
# Verify it's gone

And finally, let’s setup the new remote

git remote add origin git@bb:username/myproject.git