Using multiple GitHub accounts from a single macOS/Linux account

Let’s say you’re stuck working from home due to an ongoing apocalypse. Let’s say that you use separate GitHub accounts for personal projects vs. work (for one of any number of reasons), and that when you’re working from home you’re using a personal computer. Let’s say that for Reasons it’s not feasible for you to juggle multiple user accounts on said computer, and you need to be able to access both of your GitHub accounts without a lot of hassle.

The main problem is that GitHub ties your ssh key to your account (out of necessity), but all connections to GitHub are via the master git@github.com account, so there’s no easy way to differentiate which key to use at runtime.

So, here’s how I managed to set things up so that I could select a GitHub account on a per-shell basis.

First, create a separate ssh key for the work account:

ssh-keygen -f $HOME/.ssh/work-key   # can be work email address or whatever
cat $HOME/.ssh/work-key.pub

Then associate that key with your GitHub account.

Next, you’ll need an ssh wrapper command that uses that key. I put my work-from-home sandbox in $HOME/wfh and created this script, $HOME/wfh/wssh:

#!/bin/sh

exec ssh -i "$HOME/.ssh/work-key" "$@"

I also made $HOME/wfh/wgit:

#!/bin/sh

GIT_SSH=$(cd $(dirname "$0") && pwd)/wssh exec git "$@"

With these things I can use the wgit script to run one-off commands. However, this doesn’t completely satisfy the use case, since some of the deploy/run scripts run further git commands, so they need $GIT_SSH to be set accordingly. It’s also helpful to override the default name and email address for commits, in case you forget to override them for the git client configuration. So, to that end, I wrote this script, $HOME/wfh/setup.sh:

wdir="$(cd $(dirname $0) && pwd)"
export GIT_SSH="$wdir/wssh"
export GIT_AUTHOR_NAME="(my name at work)"
export GIT_AUTHOR_EMAIL="(my work email address"
export PS1="(work) $PS1"

When I want to enter my work-from-home not-really-a-sandbox, I run:

. $HOME/wfh/setup.sh

and then that shell is configured to use my work credentials and identity.

There’s probably an easier way to set this up; in retrospect I should have made a $HOME/wfh/bin directory that contains ssh and git wrapper scripts that set the appropriate environment variables, and made the sandbox init script simply prepend that directory to my path.

Or, really, I could have just set up a new user account, but that would have been annoying as heck for dealing with my various software licenses and user configuration and whatever.

Anyway, a bigger problem is figuring out how to get Fiona to stop sitting on my arms while I’m trying to work.

Comments

Before commenting, please read the comment policy.

Avatars provided via Libravatar