Skip to content

Instantly share code, notes, and snippets.

@solumath
Created August 28, 2024 09:14
Show Gist options
  • Save solumath/a886315dfad89cef4976e0266186992c to your computer and use it in GitHub Desktop.
Save solumath/a886315dfad89cef4976e0266186992c to your computer and use it in GitHub Desktop.
Multiple Git accounts with SSH

How to setup multiple git accounts with SSH

Considering you have 2 different SSH keys.

Important

If you don't have the keys yet follow github tutorial and add them to your accounts.

Setup changing accounts via command

Everytime you want to change accounts you need to run this.

This will set global config to use email + name + specific ssh key. Replace [email protected], USERNAME, PRIVATE_KEY with your own.

git config --global user.email "[email protected]" && git config --global user.name "USERNAME" && git config --global core.sshCommand "ssh -i ~/.ssh/PRIVATE_KEY"

Or create an alias in .bashrc

personal_git='git config --global user.email "[email protected]" && git config --global user.name "USERNAME" && git config --global core.sshCommand "ssh -i ~/.ssh/PERSONAL_PRIVATE_KEY"'
work_git='git config --global user.email "[email protected]" && git config --global user.name "USERNAME" && git config --global core.sshCommand "ssh -i ~/.ssh/WORK_PRIVATE_KEY"'

Setup changing accounts based on directory

Important

Works only on git > 2.13

Create file ~/your_path/personal/.gitconfig_personal and ~/your_path/work/.gitconfig_work with contents

[user]
    email = [email protected]
    name = USERNAME
[core]
    sshCommand = ssh -i ~/.ssh/PRIVATE_KEY

At the end of ~/.gitconfig add these lines and replace with respective names of your files and path.

[includeIf "gitdir:~/PERSONAL_FOLDER/"]
    path = ~/your_path/.gitconfig_personal
[includeIf "gitdir:~/WORK_FOLDER/"]
    path = ~/your_path/.gitconfig_work

Now try pulling private repo in each to check that you set it up correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment