Using different Git accounts in the same computer

When you use different emails for personal and work projects, it’s easy to mess up your Git repos committing to them with the wrong user. This is how to fix that

Image for post
Image for post
Photo by Todd Quackenbush on Unsplash

If it’s already happened

If you’ve committed to a personal project (with only you as a committer) with your work email, here’s how to rewrite history for that repo (from this Stackoverflow answer).

This is the one I used and worked like a charm.

git filter-branch -f --env-filter "
GIT_AUTHOR_NAME='Newname'
GIT_AUTHOR_EMAIL='new@email'
GIT_COMMITTER_NAME='Newname'
GIT_COMMITTER_EMAIL='new@email'
" HEAD

If there are multiple committers, don’t use the previous one or you’ll rewrite also the commits that weren’t made by you, use this one instead (source)

git filter-branch --commit-filter '
if [ "$GIT_COMMITTER_NAME" = "<Old Name>" ];
then
GIT_COMMITTER_NAME="<New Name>";
GIT_AUTHOR_NAME="<New Name>";
GIT_COMMITTER_EMAIL="<New Email>";
GIT_AUTHOR_EMAIL="<New Email>";
git commit-tree "$@";
else
git commit-tree "$@";
fi' HEAD

Disclaimer: if you mess up your repo doing this, don’t ask me how to fix these changes - I had no idea on any of this stuff until ~30 mins ago :)

Avoid it from happening again in the future

~/.gitconfig is where Git stores the global config variables.

If you’ve added your company email after your personal one doing something like

git config --global user.name "Your Name"
git config --global user.email "name@company.co"

If you look into it and you have this problem, you’ll see that name@company.co is the email that’s being used in all the commits you make in any repo

$ cat ~/.gitconfig...
[user]
name = Your Name
email = name@company.co
...

Fortunately, now Git lets you set up a custom .gitconfig file for all the repos in a directory (source).

To leave your personal email as the global one, edit the ~/.gitconfig file manually or do

git config — global user.email “your@email.com”

Then create a .gitconfig-company file in the folder where all the projects for your company are saved, containing

[user]
name = Your Name
email = name@company.co

And finally, to tell git to use that config on repos saved in that folder, add these lines to your ~/.gitconfig file

[includeIf "gitdir:~/CODE/Company/"]
path = ~/CODE/Company/.gitconfig-company

That should do it!

Related, with more info on how to set up different SSH keys for each Git identity

Freelance data scientist and software developer. On Twitter: @xoelipedes.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store