How to use specific private SSH key in git commands

When you run git or ssh commands, it will first look ssh key from ~/.ssh folder. This is default folder ssh get keys from.

While working with multiple git clients, you might need to use different SSH keys for different clients.

In this article, we will discuss how to use specific SSH key. There are ways you can do it. We will discuss on them one by one.

SSH config file

By default, SSH will search for ~/.ssh/config file. So we will create file using nano command.

nano ~/.ssh/config

In this file, we will create alias for specific client.

Host github
    Hostname github.com
    IdentityFile ~/.ssh/github/id_rsa
    IdentitiesOnly yes
    User username
Host gitlab
    Hostname gitlab.com
    IdentityFile ~/.ssh/gitlab/id_rsa
    IdentitiesOnly yes
    User username

Make sure you have enough permission for the file. Else you can change file permission with chmod command.

sudo chmod -R 600 ~/.ssh/github/id_rsa

Now you can use git commands like:

git clone [email protected]:jiteshmeniya/TCPDF-Laravel-Digital-Signature-Certificate.git

Using environment variable GIT_SSH_COMMAND

The second option is to use GIT_SSH_COMMAND environment variable. This will use specific ssh key instead of default key.

ssh-agent bash -c 'ssh-add ~/.ssh/github/id_rsa; git clone [email protected]:jiteshmeniya/TCPDF-Laravel-Digital-Signature-Certificate.git'

 

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment