When working with multiple Git accounts, you need to set up separate SSH keys and configure them properly. This guide will walk you through the process.
Generate SSH Keys for Each Account
Run the following commands to generate unique SSH keys for each Git account:
ssh-keygen -t ed25519 -C "user1@example.com" -f ~/.ssh/id_ed25519_user1_github
ssh-keygen -t ed25519 -C "user2@example.com" -f ~/.ssh/id_ed25519_user2_github
ssh-keygen -t ed25519 -C "user3@example.com" -f ~/.ssh/id_ed25519_user3_bitbucket
- Replace the email (user1@example.com, user2@example.com, etc.) with the email address associated with each account.
- -f specifies the file name for the key pair.
Add Public Keys to Git Hosting Platforms
For each generated key, add the corresponding public key (~/.ssh/id_ed25519_userX_github.pub) to the SSH settings in your respective Git hosting platform (e.g., GitHub or Bitbucket).
Configure SSH for Multiple Accounts
To link the private keys to their respective accounts, create or update the SSH config file in the ~/.ssh directory:
touch ~/.ssh/config
Add the following configuration to the file:
# Configuration for user1's GitHub account
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_user1_github
# Configuration for user2's GitHub account
Host github-secondary
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_user2_github
# Configuration for user3's Bitbucket account
Host bitbucket.org
HostName bitbucket.org
User git
IdentityFile ~/.ssh/id_ed25519_user3_bitbucket
- Host: Alias to identify the account (e.g., github-secondary).
- HostName: The actual hostname of the Git service.
- IdentityFile: Path to the private key for the account.
Test the SSH Connection
Test your SSH configuration to ensure everything works correctly:
- For the default GitHub account:
ssh -T git@github.com
- For the secondary GitHub account:
ssh -T git@github-secondary
- For the Bitbucket account:
ssh -T git@bitbucket.org
If successful, you’ll see a message confirming the connection.
Clone Repositories Using Specific Accounts
When cloning repositories(For example https://github.com/username/repository.git), use the corresponding Host alias defined in the SSH config file. For example:
- Cloning using the default GitHub account:
git clone git@github.com:username/repository.git
- Cloning using the secondary GitHub account:
git clone git@github-secondary:username/repository.git
- Cloning using the Bitbucket account:
git clone git@bitbucket.org:username/repository.git
Final Notes
- Ensure the SSH agent is running (eval $(ssh-agent -s)) and keys are added using ssh-add if needed.
- Double-check file permissions for private keys (chmod 600 ~/.ssh/id_ed25519_*) to avoid issues.