Committing to git as a different user

I have two accounts on git, one for work, and one for personal use. On my work laptop, I push all my commits to origin on my work account. But as part of learning Scala for work, I created a sandbox where I could play around with Scalatra. I created a repository on git for my sandbox, under my personal user name. I wanted to push all commits in this repository under my personal account. I had gotten all this working and promptly forgot how I set it all up. Unfortunately, it stopped working, so I set it all up again.

I first removed the [Credential] section of my git config:
git config –global –edit

It had been using credential.helper osxkeychain and my keychain had been hosed before. This was probably why everything stopped working. I decided to start from scratch and forgo using keychain.

The first step was to create the ssh key and then adding it to git, as documented here

The second step was to tell git to use my personal account for my scalatra sandbox repository. For some reason, git was still trying to use my work email to push commits to my sandbox repo. After much frustration and googling, I found the answer on stack overflow

The missing step was to edit ~/.ssh/config and add two sections, one for work, and one for personal:

#personal
Host github.com-jieyangh
     HostName github.com
     User git
     IdentityFile ~/.ssh/id_rsa
     IdentitiesOnly yes
   
#work
   Host github.com-jiehu
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_work

Note that you always connect to git as the user “git”.

Next I deleted my remote origin and re-added it, this time specifying the key to use:

git remote remove
git remote add origin git@github.com-jieyangh:jieyangh/scalatra-sample-API.git

where git@github.com-jieyangh was the host value specified under ~/.ssh/config and jieyangh/scalatra-sample-API.git was the username followed by the git repo (git could not find the repo unless it was preceded by my username).

After that, I was able to push to my work repos as my work account, and my sandbox under my personal account once more.

Leave a Reply

Your email address will not be published. Required fields are marked *