Automatically add ssh key based on directory I'm in

I have two GitHub accounts. One for personal use, and another for business. Each is set up with its own SSH key gh_personal and gh_business inside ~/.ssh.

I have a personal project that sits in ~/code/bejebeje. Each time I go to work on that project, I have to remember to run the following:

eval `ssh-agent -s`       

Followed by:

ssh-add ~/.ssh/gh-personal

Only then can I do things like git pull and git push.

You guessed it, I always forget to do that.

Is there a way I can tell my Linux system to do that automatically whenever I go to the directory ~/code/bejebeje?

I’m on Arch Linux.

Asked By: J86

||

You can create an ssh_config AKA ~/.ssh/config to match different addresses like the following:

Host *
  Protocol                 2
  PreferredAuthentications publickey,password
  VisualHostKey            yes

Host work_gh
  HostName                 github.com
  IdentityFile             ~/.ssh/id_rsa.work
  IdentitiesOnly           yes
  ForwardAgent             no
  LogLevel                 DEBUG

Host personal_gh
  HostName                 github.com
  IdentityFile             ~/.ssh/id_rsa.personal
  IdentitiesOnly           yes
  ForwardAgent             no
  LogLevel                 DEBUG

This configuration will also not require ssh-agent nor will it try to use the agent because of IdentitiesOnly consult man ssh_config for more information on the options that you can set with ssh_config

Getting back to git, you can use the name "personal_gh" as the host name in the address you want to clone:

git clone git@personal_gh:mypersonalghuser/things.git

You can also change existing git repositories:

git remote show origin
* remote origin
  Fetch URL: git@personal_gh:mypersonalghuser/things.git
  Push  URL: git@personal_gh:mypersonalghuser/things.git
  HEAD branch: master
  Remote branch:
    master tracked
  Local branch configured for 'git pull':
    master merges with remote master
  Local ref configured for 'git push':
    master pushes to master (up to date)

If you have repositories that you need to push to both accounts, I would suggest adding more than one remote in git and pushing like:

git push my-dest-account-1 master
git push my-dest-account-2 master

you can add remotes with:

git remote add --help

In any case, the SSH key that gets used will be matched based on the host name part of the git address if you configured it in your ssh client configuration, usually ~/.ssh/config

Answered By: Paige Thompson
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.