Automatically switch GIT Author between work and personal emails

Jamie Haywood
2 min readJun 11, 2020
Git logo. https://commons.wikimedia.org/wiki/File:Git-logo.svg

A problem I’ve frequently encountered is that my personal email account gets attached is attached to commits I make to work repositories.

The commands I use in this article are all done in MacOS terminal with BASH v5.0.17.

File Structure Overview

The general file overview of the structure that I use is below. Make sure you substitute work/ and personal/ with the names of the folders that contain your respective repos.

user/
├── .gitconfig
├── work/
│ └── .gitconfig
└── personal/
└── .gitconfig

Show me the commands!

The .gitconfig in the user/ folder is the global GIT config, which is deferred to across all GIT repos. In here we want to delete any global author properties that might be in here. To do this:

git config --global --unset user.name
git config --global --unset user.email

Next we want to add a .gitconfig file in our work/ and personal/ folders:

touch ~/work/.gitconfig ~/personal/.gitconfig

Now we want to add the requisite email and name to each respective .gitconfig:

nano ~/work/.gitignore

And add the following lines, substituting email and name:

[user]
email = USERNAME@WORK-EMAIL.com
name = FIRSTNAME LASTNAME

And do the same to the ~/personal/.gitignore changing your email and/or name to what you would like to use for your personal repos

Automatic switching

To get GIT to switch automatically to your work credentials when in ~/work/ subdirectories and personal credentials in~/personal/ subdirectories we need to write some lines to our global .gitconfig

nano ~/.gitconfig

We want to add the following lines:

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

These lines tell the Global GIT config to use the config in the respective ~/work and ~/personal directories.

Finished!

I hope you found this helpful. It’s certainly helped me from committing work using my personal email and personal commits using my work email. It’s important to note that you can repeat this structure for as many directories as you like — just follow the steps 💪

--

--