Martin Frost

Custom core.sshCommand in git config per path

Published:

I recently figured out what to put in my global ~/.gitconfig in order to be able to use multiple github accounts from the same user on my laptop, that works neatly with the rest of my setup.

First off, I tend to not just dump all code repos into the same directory, but categorize them at least one step further. It's something like ~/code/{source}/{org}/{repo}, so everything that's on github would go under ~/code/github, stuff from codeberg would go under ~/code/codeberg, and so on.

One of my problems with this is the fact that I have to use a separate github account for work stuff, and github only allows one account per SSH key.

GitHub's documentation suggests to either use HTTPS and a custom credentials-helper along with Personal Access Tokens in order to work with repos from multiple accounts, or to set up a shell wrapper that configures the GIT_SSH_COMMAND environment variable to something like ssh -i PATH/TO/FILE -o IdentitiesOnly=yes

I really prefer working with git over SSH, but I really don't like configuring thing per repo because when I eventually forget it for some repo, I might accidentally commit something using the wrong committer email, or try to push using the wrong key, and get sidetracked on why I don't have access to the repo in question.

Anyway, since I organize code locally on my machine in the way I just mentioned, I figured this should be possible by using the includeIf thing in my global .gitconfig.

After a bit of digging, I found out that since version 2.10.0, which was release in September 2016, there is a core.sshCommand config setting that does the same thing as the GIT_SSH_COMMAND environment variable.

Since I'm already using includeIf (available in git from v2.13.0, May 2017), I can combine these two into something like this:

# ~/.gitconfig

[includeIf "gitdir:~/code/github/WORK_ORG/"]
    path = ~/.gitconfig.work
[includeIf "gitdir:~/code/github/ANOTHER_ORG/"]
    path = ~/.gitconfig.personal

And then have the ~/.gitconfig.work look something like this:

# ~/.gitconfig.work

[core]
    sshCommand = "ssh -i PATH/TO/WORK_SSH_KEY -o IdentitiesOnly=yes -F /dev/null"
[user]
    email = my.name@example.com

And with that, I can now cd ~/code/github/WORK_ORG and clone my work repos, and it will automatically run ssh with the correct key which will identify my work user, and when I cd into some other repo, for example a personal one, it will use my private SSH key to authenticate as my private account.