Setting up local git config to use a different user in personal and work projects

So it's never too late to discover basic config usage of your daily tools I guess.. I sometimes need to push changes on both work and personal related repositories. And of course I don't want to be using the same email to identify myself on those respositories.

Format

Git uses configuration file to manage all of its possible configuration options. The format of this file is INI and it can be structured with keys and sections:

name=value
[section]
a=a
b=b

Configuration scopes

3 scopes are available to personalize the configuration of your projects:

Git will take properties from the local scope in priority, then global if they do not exists in local and then in system.

Displaying options

You can use git config --list --show-origin in one of your repository to display all git configuration variables set.

--show-origin will give you the info from where one particular option is set.

$ git config --list --show-origin
file:/home/user/.gitconfig    user.name=User Name
file:/home/user/.gitconfig    user.email=Email
file:/home/user/.gitconfig    core.autocrlf=input
file:/home/user/.gitconfig    pull.rebase=true
file:.git/config        core.ignorecase=true
...

In this example you can see that variables:

and variable:

Setting up a different config depending on path

An option of git config includeIf allow us to personalize the config file to use depending on:

So in my case I wanted to use by default my work configuration and for projects located in ~/projects/perso/ I want to use my personal email.

My global config file in ~/.gitconfig contains:

[user]
	name = Emmanuel Balpe
	email = mywork@email.com
	useConfigOnly = true
[gc]
	autoDetach = false
[core]
	autocrlf = input
	fileMode = false
[pull]
	rebase = true
[includeIf "gitdir:~/projects/perso/"]
	path = ~/.git/.gitconfig-perso

Notice the path ~/projects/perso/, trailing / is important.

I created a config file in ~/.git/.gitconfig-perso containing my personal info:

[user]
	name = Emmanuel Balpe
	email = m4nu56@gmail.com
$ git config --list --show-origin
file:/home/user/.gitconfig    user.name=Emmanuel Balpe
file:/home/user/.gitconfig    user.email=mywork@email.com
file:/home/user/.gitconfig    user.useconfigonly=true
file:/home/user/.gitconfig    gc.autodetach=false
file:/home/user/.gitconfig    core.autocrlf=input
file:/home/user/.gitconfig    core.filemode=false
file:/home/user/.gitconfig    pull.rebase=true
file:/home/user/.gitconfig    includeif.gitdir:~/projects/perso/.path=~/.git/.gitconfig-perso

So now when I push in any repository inside ~/projects/perso I'm using my personal git config.

← Back to home