Git: Setup Git for multiple emails

Programming, Technology

Problem:

The common way we configure Git email address at our machine is:

git config --global user.email user@email.com

It’s only for 1 email address and it will become a challenge when you have 2 (or more) Git accounts for different purposes e.g: for work project and for personal project. Remote repository only calculates commit contribution if configured email address matches with account’s email address.

One of solution I think of is to re-configure email address by re-running above terminal command each time before committing. However, it seems not efficient. There is another way to solve it.

Solution:

Alternative#1: Create individual .gitconfig inside each repository 

From the root directory of each repo, run

git config user.name "Your Name Here"
git config user.email your@email.com

Meanwhile keep the default configuration at ~/.gitconfig

Alternative#2: Create multiple .gitconfig for different account 

We utilize Git config conditional includes and personally, I prefer this solution.

Suppose we have 2 Git accounts: for working project and personal project.

I want to keep ~/.gitconfig for global configuration and use it for personal purpose.

For working purpose, I create new file .gitconfig in other directory.

Here are the steps to do it:

1. Modify file ~/.gitconfig and add [includeIf] section:

[user]  
name = Your Name Here
email = your@email.com
[includeIf "gitdir:~/nioRepo"]
path = ~/gitconfig-work/.gitconfig

2. Create new directory ~/gitconfig-work/ and Create new file .gitconfig inside that directory

3. Add this below inside file .gitconfig

[user]    
email = work@email.com

4. Sample result

5. Done

Reference:

 

Leave a Reply

Your email address will not be published. Required fields are marked *