How to Use Different SSH Keys for GitHub and Bitbucket on the Same Machine

When working on multiple projects that use different Git hosting services like GitHub and Bitbucket, we sometime need to configure separate SSH keys on the same machine. This step-by-step guide will show you how to set up multiple SSH keys on Ubuntu 22.04 for managing different Git accounts seamlessly. I have done this for ubuntu system but this approach is more or less for windows and mac os.
Step 1: Check Existing SSH Keys
Before generating new SSH keys, check if you already have any keys in your system:
ls -l ~/.ssh/
Step 2: Generate a New SSH Key for GitHub
Since you already have an SSH key for Bitbucket, create a separate key for GitHub:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
When prompted:
Do not overwrite the existing key (id_rsa).
Instead, save it as id_rsa_github (or another recognizable name).
Example:
Enter file in which to save the key (/home/your-user/.ssh/id_rsa): /home/your-user/.ssh/id_rsa_github
This will generate:
~/.ssh/id_rsa_github (private key)
~/.ssh/id_rsa_github.pub (public key)
Step 3: Add Your New SSH Key to GitHub
- Copy your public key:
cat ~/.ssh/id_rsa_github.pub
- Go to GitHub → Settings → SSH and GPG keys.
- Click “New SSH key“, paste the copied key, and save it.
Step 4: Configure SSH to Use the Correct Key
To ensure Git uses the correct key for each service, configure SSH by editing (or creating) the
~/.ssh/config file:
nano ~/.ssh/config
Add the following:
# Bitbucket Configuration
Host bitbucket.org
HostName bitbucket.org
User git
IdentityFile ~/.ssh/id_rsa
# GitHub Configuration
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
Save and exit (Ctrl + X
, then Y
and Enter
).
Step 5: Add SSH Keys to the SSH Agent
To ensure the keys are loaded, start the SSH agent:
eval "$(ssh-agent -s)"
Save and exit (Ctrl + X
, then Y
and Enter
).
Then add both keys:
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_github
Step 6: Test the SSH Connections
Verify that SSH is correctly using each key:
ssh -T git@bitbucket.org
Expected output:
logged in as
ssh -T git@github.com
Expected output:
Hi
Step 7: Clone Repositories Using the Correct SSH Key
When cloning repositories, always use the correct SSH URL:
git clone git@bitbucket.org:your-bitbucket-username/repository.git
For GitHub:
git clone git@github.com:your-github-username/repository.git