How to set up multiple ssh keys (accounts) in multiple workspaces

https://blog.gitguardian.com/8-easy-steps-to-set-up-multiple-git-accounts/

  • Create ssh keys using key-gen (id_personal, id_prof)
  • Add keys using ssh-agent
  • Create config file in ~/.ssh/config
# ~/ssh/config
Host *
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/<personal_key>

Host *
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/<work_key>
  • Copy public keys to github accounts
  • Create config files as such
# this is directory structure
/parent_dir/
|__.gitconfig # global config
|__work_dir/
     |_.gitconfig.work. # work specific config
|__personal_dir/
    |_.gitconfig.pers. # personal specific config
  • gitconfig.pers or gitconfig.work should look something like this
# /parent_dir/personal_dir/.gitconfig.pers
 
[user]
email = your_pers_email@example.com
name = Your Name
 
[github]
user = "githubusername"
 
[core]
sshCommand = "ssh -i ~/.ssh/<personal_key>"
  • global config should look like this
# /parent_dir/.gitconfig
 
[includeIf "gitdir:~/myprojects/personal_dir/"] # include for all .git projects under personnal/ 
path = ~/myprojects/personal_dir/.gitconfig-pers
 
[includeIf "gitdir:~/myprojects/work_dir/"]
path = ~/myprojects/work_dir/.gitconfig-work
 
[core]
excludesfile = ~/.gitignore      # valid everywhere