Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sainak/bbf13f0bc0063f7e1b1aaea8bf626ec9 to your computer and use it in GitHub Desktop.
Save sainak/bbf13f0bc0063f7e1b1aaea8bf626ec9 to your computer and use it in GitHub Desktop.
Using multiple github accounts with ssh keys

Using multiple github accounts with ssh keys

  1. Generate ssh key pairs for accounts and add them to GitHub accounts.

  2. Edit/Create ssh config file (~/.ssh/config):

    # Default github account: user01
    Host github.com
       HostName github.com
       IdentityFile ~/.ssh/key_for_user01
       IdentitiesOnly yes
       
    # Other github account: work-user01
    Host github-workuser01
       HostName github.com
       IdentityFile ~/.ssh/key_for_workuser01
       IdentitiesOnly yes
    
  3. Test your connection

    ssh -T [email protected]
    ssh -T git@github-workuser01

    With each command, you may see this kind of warning, type yes:

    The authenticity of host 'github.com (192.30.252.1)' can't be established.
    RSA key fingerprint is xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:
    Are you sure you want to continue connecting (yes/no)?

    If everything is OK, you will see these messages:

    Hi user01! You've successfully authenticated, but GitHub does not provide shell access.
    Hi workuser01! You've successfully authenticated, but GitHub does not provide shell access.

    you can delete all cached keys if you are having issues

    ssh-add -D
  4. Now all are set, just clone your repositories

    git clone git@github-workuser01:org2/project2.git /path/to/project2
    cd /path/to/project2

    While cloning the repo remember to replace the host in the clone url for this case github.com -> github-workuser01

    For already cloned repo you can do this

    git remote set-url origin git@github-workuser01:org2/project2.git

    To do this automatically append this in your git config in ~/.gitconfig or ~/.config/git/config

    [url "git@github-workuser01:work-user01"]
        insteadOf = [email protected]:work-user01
    [url "git@github-workuser01:org2"]
        insteadOf = [email protected]:org2
    
  5. To set git email based on folder name read this

Done! Goodluck!

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