Separating git config for several git servers

How to configure you .gitconfig to use different accounts for several git servers.

GitLab, GitHub and git logo

Some time ago I did edit some docs on some GitHub project. I realized afterward that I had pushed my work email to a GitHub repo which I actually do not want.

So I have looked up how I can separate my work on GitHub and the work on the internal Gitlab server which is only for work.

Before the new setup, I was keeping all my git repositories in one git folder ~/git. But now I found a pretty flexible and neat solution for myself.

Folder structure per git server

First, you have to separate the folders for your different git servers like GitHub, internal Gitlab, public Gitlab, whatever you use.

I am using a folder  each, one for GitHub and one for our internal Gitlab server, and put the respective projects in there:

├── github
└── gitlab-work

main gitconfig

Your regular .gitconfig will just reference the gitconfig for each older you have set up and will use the respective config when working in that directory. That is what the includeif statement is for:

[includeIf "gitdir:~/github/"]
  path = ~/.gitconfig-github

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

	defaultBranch = main

You can also specify some sane defaults in the general .gitconfig. I just added the default branch name to be main for both directories.

Secondary gitconfig

Now you need to create a separate .gitconfig for GitHub and Gitlab. Here is my .gitconfig-gitlab-work:

	name = Andrej Friesen
	username = USERNAME
    editor = vim
    default = current

And here we have the .gitconfig-github:

	name = Andrej Friesen
	username = ajfriesen
    editor = vim
    default = current

As you can see I could have moved the [core] and [push] part from both of those gitconfigs to my global one.
That just happened because git asked me while I was working in the terminal. git was smart enough to add the config only to the respective project I was working on. So I did this twice, once for GitHub and once for internal GitLab.

Obviously you can do this for as many git servers as you like. I bet there is also another hidden gem but that works just fine for now. Hope this helps.

Have a great day!⌨