If you’re working with Git, you might want to use a different SSH key for your git shell commands. This is because SSH keys are used to protect your work from being stolen by someone else.
Using SSH keys is more secure than passwords, and that applies to Git as well. Unlike a password however, it’s harder to change your SSH key, or manage multiple keys. By editing your SSH config though, you can connect to multiple Git repositories with different keys.
How Does SSH Work With Git?
Git doesn’t just use your private key to authenticate when you use SSH instead of HTTPS—it actually establishes a real SSH connection to the remote server. It does this silently, so you may not be aware of the commands it’s running, but it uses ssh under the hood.
Because it uses your default ssh command, it will act like you just ran it yourself, and use your default key in ~/.ssh/id_rsa. This probably isn’t what you want if you’re here reading this, so to change it, you’ll need to edit SSH’s configuration—not Git’s.
Making a New SSH Key
You’ll need one to do this in the first place, and doing this is pretty easy. Simply run ssh-keygen and specify a new key name with the -f flag. This will create a private key and a public key with the .pub extension.
Editing ~/.ssh/config
SSH’s config file allows setting “Hosts” which will match based on what you’re connecting to and allow modification of the file that ssh uses.
This will let you use a different SSH key than your primary one for all requests going to github.com, but what if you want to use two different keys for separate Git repositories? For example, one for your work account, and one for your personal account.
Well, you’ll need to define two configurations with different names, using the same host:
Usually this would result in a conflicting configuration, but Git provides a way around this. If you have a remote repository like Github linked with your local repo, delete it:
Then, instead of adding github.com as the remote, replace it with the name of the Host in the SSH configuration file. Git will recognize this, and use this SSH host to connect. You can set separate hosts per-repository.
Manually Overriding
If you don’t want to mess with SSH config, or just want to override it temporarily, Git also provides the GIT_SSH_COMMAND environment variable. You can
Any Git commands you run afterwards in the same shell session will use that SSH command instead of the default one. You can also set an entirely different SSH binary with GIT_SSH.