DEV Community

Cover image for Git SSH keys setup
Željko Šević
Željko Šević

Posted on • Originally published at sevic.dev

Git SSH keys setup

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Verify the connection to a provider:

ssh -T git@github.com
ssh -T git@bitbucket.org
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

Reload the shell configuration, then run the alias before working with that provider:

source ~/.zshrc
ssh-github
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

If authentication fails, run the matching alias (for example, ssh-github) and try again.

Top comments (0)