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
.gitconfigin the home directory. This contains your personal git configuration - You have a directory
~/Projects/companyfor all company repositories. You want to use your company identity for all these projects. - You have a directory
~/Projects/ossfor 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
~/Projectsdirectory 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 setupAnd 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.