Git Configuration for Using Different Settings Based on Multiple Git Services

Sometimes, different Git configurations are needed for personal GitHub projects and company GitLab projects. For example, I want to use my company username, heqiangx, for GitLab projects but my English name, Alan He, for GitHub. How can this be achieved? The solution is to switch Git configurations automatically based on the repository address.

Manually configuring each repository? Sorry, I dislike inefficient methods.

.ssh/config

Why mention this file first? I initially misunderstood its purpose. Previously, I relied on the configurations here to ensure commits to different repository services used different tokens, leading me to believe this file could solve the problem.

However, this is incorrect because the core issue is:

.ssh/config addresses authentication, as Git uses SSH for authentication. However, my need for personalized Git settings isn’t related to authentication but rather to Git configurations, which must be resolved using Git’s configuration files.

.gitconfig

Main Configuration

Note: open the configuration file in the ~ directory and paste the following sections. Once saved, Git operations will follow different personalized configurations based on the repository’s path.

1
2
3
4
5
6
7
// ...
[includeIf "gitdir:~/Documents/GitHub/"]
path = ~/.gitconfig-personal
[includeIf "gitdir:~/Documents/GitLab/"]
path = ~/.gitconfig-work

// ...

Personalized Configuration

Below is the .gitconfig-personal configuration. The .gitconfig-work is similar, differing only in the name and email fields.

1
2
3
[user]
name = Alan He
email = alan@1991421.cn

Notes

The solution above offers a one-time setup to ensure all projects under different directories follow specific Git configurations. However, note that these are “global configurations.” If a repository has its particular settings, it will override these configurations. To remove the repository-specific settings and use the global configurations, you can do the following:

1
2
3
4
5
// Remove the current user.name configuration
git config --unset user.name

// List all current configurations in the repository
git config --list

Final Thoughts

  • Personalized Git configurations for individual repositories are rare or unnecessary. My primary need is to separate configurations for company and personal projects.
  • The solution above is highly valuable because it enables multiple global configurations to apply automatically based on the type of project.
  • Of course, you could configure each project individually if needed, but the effort involved would be significantly higher. Thus, the best approach is to choose the most suitable method based on the situation.