Nothing is more embarrassing than pushing code to your company repository with your personal email address, or vice versa. Manually running git config user.email in every folder is tedious. Git has a built-in feature called includeIf that can automatically switch your config based on the folder path.
Why This Matters
- Prevent mix-ups: Automatically use the correct identity for work vs. personal projects.
- Zero friction: No need to remember to run config commands when starting a new project.
- Clean history: Keep your commit graphs organized by correct authorship.
Step 1: Organize Your Folders
First, ensure your projects are separated by directory.
# Example structure
~/code/
├── personal/
│ └── my-blog
└── work/
└── company-websiteStep 2: Create Separate Config Files
Create dedicated configuration files for your different identities.
# Create a config for work
cat > ~/.gitconfig-work << EOF
[user]
name = "Your Work Name"
email = "work@company.com"
EOF
# Create a config for personal
cat > ~/.gitconfig-personal << EOF
[user]
name = "Your Personal Name"
email = "personal@email.com"
EOFStep 3: Configure the Main .gitconfig
Edit your main global Git configuration file to include these conditionally.
# Open your main config
nano ~/.gitconfigAdd the includeIf sections to the bottom of the file:
[includeIf "gitdir:~/code/work/"]
path = ~/.gitconfig-work
[includeIf "gitdir:~/code/personal/"]
path = ~/.gitconfig-personalNote: The path in
gitdirmust end with a trailing slash/.
Step 4: Test Your Setup
Navigate to your folders and verify which identity is active.
# Check work folder
cd ~/code/work
git config user.email
# Should output: work@company.com
# Check personal folder
cd ~/code/personal
git config user.email
# Should output: personal@email.com⚠️ Important Reminders
- Trailing Slash: The
gitdir:path must end with a slash. Without it, the pattern matching might not work correctly for subdirectories. - Global Fallback: Any folder not matching your
includeIfrules will use the default settings in your main~/.gitconfig. - Existing Repos: This method works for new and existing repos instantly. You don't need to re-run
git configinside existing repos.
Pro Tips
- You can use environment variables or specific project names for more complex rules.
- Combine this with the SSH config guide to fully automate your workflow (SSH keys handle access,
includeIfhandles identity). - Use
git config --list --show-originto see exactly which config file is setting a value.
Set it up once, and never worry about committing with the wrong email again! 🚀