Step 1 – Create a New SSH Key
We need to generate a unique SSH key for our second GitHub account.
ssh-keygen -t rsa -C "your-email-address"
Be careful that you don’t over-write your existing key for your personal account. Instead, when prompted, save the file as
id_rsa_SECOND. In my case, I’ve saved the file to
~/.ssh/id_rsa_cristianfierro.
Step 2 – Attach the New Key
Next,
login to your second GitHub account, browse to “Account Overview,” and
attach the new key, within the “SSH Public Keys” section. To retrieve
the value of the key that you just created, return to the Terminal, and
type:
clip < ~/.ssh/id_rsa_cristianfierro.pub. That copies public key, and then you have to paste this into the GitHub textarea. Feel free to give it any title you wish.
Next, because we saved our key with a unique name, we need to tell SSH about it. Within the Terminal, type:
ssh-add ~/.ssh/id_rsa_SECOND. If successful, you’ll see a response of “Identity Added.”
If you are using Windows maybe you will get this error: “Could not open a connection to your authentication agent”
Solution:
In the CMD window, type the following command:
cd path-to-Git/bin (for example,cd C:\Program Files\Git\bin)
bash
exec ssh-agent bash
ssh-add path/to/.ssh/id_rsa_cristianfierro
Step 3 – Create a Config File
We’ve
done the bulk of the workload; but now we need a way to specify when we
wish to push to our personal account, and when we should instead push
to our company account. To do so, let’s create a
config file.
touch ~/.ssh/config
vim config
If you’re not comfortable with Vim, feel free to open it within any editor of your choice. Paste in the following snippet.
#default account
Host github.com
HostName github.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
This is the default setup for pushing to our personal GitHub
account. Notice that we’re able to attach an identity file to the host.
Let’s add another one for the company account. Directly below the code
above, add:
#cristianfierro account
Host cristianfierro.github.com
HostName github.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_cristianfierro
This time, rather than setting the host to
github.com, we’ve named it as
SECOND.github.com. The difference is that we’re now attaching the new identity file that we created previously:
id_rsa_SECOND. Save the page and exit!
Step 4 – Try it Out
It’s time to see if our efforts were successful.
When you want to clone a repository with the
SECOND account, instead of using:
git clone git@github.com:second/secondsproject.git
You should use :
git clone git@second.github.com:second/secondsproject.git
In my case:
git clone git@cristianfierro.github.com:cristianfierro/project.git
Step 5 – Change User Information
After all you have to change the information of the second repo
cd my_other_repo
git config user.name "Different Name"
git config user.email "differentemail@email.com"