SSH keys let you authenticate with Git hosts without entering a password on every push or pull. This post covers generating keys for multiple providers, loading them into the SSH agent, and cloning repositories over SSH.
For general Git commands, see the Git cheatsheet.
Generate SSH keys
Generate a separate key for each provider (for example, GitHub and Bitbucket). Run ssh-keygen for each key, set a distinct filename, and optionally add a passphrase.
ssh-keygen -f ~/.ssh/id_rsa_github
ssh-keygen -f ~/.ssh/id_rsa_bitbucket
Add public keys to providers
Copy each public key (the .pub file) and add it to the provider:
cat ~/.ssh/id_rsa_github.pub
cat ~/.ssh/id_rsa_bitbucket.pub
Activate SSH keys
Start the SSH agent and add the keys you need for the current session.
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa_github
ssh-add ~/.ssh/id_rsa_bitbucket
Verify the connection to a provider:
ssh -T git@github.com
ssh -T git@bitbucket.org
Shell aliases per provider
Add aliases to ~/.bashrc or ~/.zshrc to run the agent setup and load the correct key in one command.
alias ssh-github='eval "$(ssh-agent -s)" && ssh-add ~/.ssh/id_rsa_github'
alias ssh-bitbucket='eval "$(ssh-agent -s)" && ssh-add ~/.ssh/id_rsa_bitbucket'
Reload the shell configuration, then run the alias before working with that provider:
source ~/.zshrc
ssh-github
Clone repositories
Use the SSH remote URL when cloning. The host (github.com or bitbucket.org) determines which key the provider expects.
# git clone <REPOSITORY_URL>
git clone git@github.com:workspace/repo-name.git
git clone git@bitbucket.org:workspace/repo-name.git
If authentication fails, run the matching alias (for example, ssh-github) and try again.
Top comments (0)