All articles
git

How to Auto-Switch Git Accounts for Work and Personal Projects

Share this article

Share on LinkedIn Share on X (formerly Twitter)

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-website

Step 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"
EOF

Step 3: Configure the Main .gitconfig

Edit your main global Git configuration file to include these conditionally.

# Open your main config
nano ~/.gitconfig

Add the includeIf sections to the bottom of the file:

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

Note: The path in gitdir must 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

  1. Trailing Slash: The gitdir: path must end with a slash. Without it, the pattern matching might not work correctly for subdirectories.
  2. Global Fallback: Any folder not matching your includeIf rules will use the default settings in your main ~/.gitconfig.
  3. Existing Repos: This method works for new and existing repos instantly. You don't need to re-run git config inside 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, includeIf handles identity).
  • Use git config --list --show-origin to see exactly which config file is setting a value.

Set it up once, and never worry about committing with the wrong email again! 🚀


Comments