Run these commands to create a new .ssh folder if you don't already have one:
mkdir ~/.ssh
chmod 700 ~/.sshNavigate to the newly created .ssh folder:
cd ~/.sshssh-keygen -t rsa -C "[email protected]" -f "github-username"-t rsa: Specifies the type of key to create as an RSA key.
-C "[email protected]": Specifies an optional comment.
-f "github-username": Specifies the filename of the key.
Make sure to add a strong passphrase (store it somewhere encrypted).
Run the following command:
ssh-add ~/.ssh/<github-username>Enter the passphrase when asked.
You might not have the ssh agent running. If when running the command you get the following error:
Could not open a connection to your authentication agent., make sure to start the agent with:
eval `ssh-agent -s`It might also be possible that your key is not accessible by others:
It is required that your private key files are NOT accessible by others. This private key will be ignored.. In this case, run the following command to each generated key:
chmod 600 ~/.ssh/<github-username>The command sets the file permissions of the file ~/.ssh/<github-username> to allow only the owner of the file to read and write to the file.
Make sure to copy the generated key's .pub. One way to do this is to run:
cat ~/.ssh/<github-username>.pubSelect the key with your cursor and copy the content.
Go to GitHub > Settings > SSH and GPG keys > New SSH key.
Add a title (for example, WSL2) and paste the generated key.
Run the following command to create the configuration file and start writing on it directly in the terminal:
nano ~/.ssh/configAdd the following lines to the file, making sure to replace the placeholder text with your own:
Host <personal>
HostName github.com
User git
IdentityFile ~/.ssh/<personal>
AddKeysToAgent yes
Host <work>
HostName github.com
User git
IdentityFile ~/.ssh/<work>
AddKeysToAgent yesSuppose you have two different GitHub accounts, one for work and one for personal.
You will have a different .gitconfig file for each root folder where your projects will be stored in respectively:
Personal ~/personal/.gitconfig:
[user]
name = Personal
email = [email protected]Work ~work/.gitconfig:
[user]
name = Work
email = [email protected]Now edit the global configuration file to point to these local configurations:
nano ~/.gitconfig[includeIf "gitdir:~/work/"]
path = ~/work/.gitconfig
[includeIf "gitdir:~/personal/"]
path = ~/personal/.gitconfigTo clone a repository, run the following command:
git clone git@<added-username>:<owner-username>/<repo-name>.gitFor example, if one of my usernames is personal and I want to clone the repository my-repo from the owner my-owner, I would run:
git clone git@personal:my-owner/my-repo.git