Use separate Git identities based on directories

Photo by Mulyadi / Unsplash

This guide helps you set up different identities in Git while working on different projects based on the directory you are in.

Assumption

Let’s assume your directory structure looks like this:

~
├── .gitconfig
└── Projects
    ├── company
    │   ├── company-project-1
    │   ├── compnay-project-2
    │   └── company-project-3
    ├── oss
    │   ├── oss-project-1
    │   └── oss-project-2
    ├── personal-project-1
    └── personal-project-2
  • You have global .gitconfig in the home directory. This contains your personal git configuration
  • You have a directory ~/Projects/company for all company repositories. You want to use your company identity for all these projects.
  • You have a directory ~/Projects/oss for all your open-source repositories. And you want to use your open-source identity for these projects.
  • You have cloned all other projects directly in the ~/Projects directory without any sub-directories. You want to use your personal identity for all these projects.

Setup

A typical ~/.gitconfig looks like this:

# ~/.gitconfig

[user]
    name = User Name
    email = personal-email@gmail.com

# some more common configuration

Step 1: Create different .gitconfig files for different identities

Let’s create 2 additional config files for different git identities.

# ~/.gitconfig-company

[user]
    name = User Name
    email = user-name@company.com
# ~/.gitconfig-oss

[user]
    name = User Name
    email = oss-email@oss-project.com

Step 2: Configure Git to use different identities based on the current directory

Update your ~/.gitconfig file to include these identity files based on the directory.

# ~/.gitconfig

[user]
    name = User Name
    email = personal-email@gmail.com

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

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

# some more common configuration
⚠️
Please adjust the .gitconfig file names and directories in the above file based on your local setup

And that’s all. Now when you go into ~/Projects/company, Git will automatically load the configuration from the ~/.gitconfig-company file and append it to the existing configuration. And the same thing will happen for ~/Projects/oss projects.

Shirish Padalkar

Shirish Padalkar

Pune, India