Handling multiple GitHub accounts

This post is almost entirely based on https://trashpanda.cc/blog/2023-10-27-multiple-git-accounts-on-one-machine/.

File structure

~
├── .gitconfig <-- global
└── repos
    ├── personal/
    │   ├── .gitconfig.personal <-- personal
    │   ├── project_1/
    │   ├── project_2/
    │   └── project_3/
    └── work/
        ├── .gitconfig.work <-- work
        ├── project_1/
        ├── project_2/
        └── project_3/

The global .gitconfig can exist in ~ or ~/repos, but must be above the two separate ones.

SSH

Create new SSH keys:

Be sure to use the proper email & github username. Upload your newly created public key to GitHub.

Add something similar to this to your .ssh/config file:

# personal account
Host github.personal
  HostName github.com
  User git
  IdentityFile ~/.ssh/personal


# work account
Host github.work
  HostName github.com
  User git
  IdentityFile ~/.ssh/work

Change only the "Host" and "IdentifyFile"; "HostName" and "User" stay as they are.

gitconfigs

In your global .gitconfig file, remove [user] email, name, [github] user, and [credential] username. Instead, insert the following:

[includeIf "gitdir/i:~/repos/personal/"]
    path = ~/repos/personal/.gitconfig.personal
[includeIf "gitdir/i:~/repos/work/"]
    path = ~/repos/work/.gitconfig.work

Create two files, ".gitconfig.personal" and "gitconfig.work" in the specified locations, with the following:

[user]
  email = <email address associated with the Github account>
  name = <your name>

[github]
  user = <your github username>

[credential]
  username = <your github username>

Cloning repos

Going forward, whenever cloning a repo, instead of git@github.com, use git@github.personal or git@github.work instead.

Add this to your .zshrc or .bashrc to avoid accidentally cloning from github.com:

git() {
    if [[ "$1" == "clone" && "$2" == *"github.com"* ]]; then
        echo "Error: Use github.personal or github.work instead of github.com"
        return 1
    fi
    command git "$@"
}

Another useful reference is https://andrewstiefel.com/working-multiple-github-accounts/.

Home | Back to blog

This work is licensed under CC BY-NC 4.0 Creative Commons BY-NC image