Multiple git profiles without manually switching the config

sabbirshouvo

Sabbir Hasan

Posted on January 4, 2023

Multiple git profiles without manually switching the config

We often need to maintain multiple git client. For myself I use Github for my personal work and bitbucket for job. In a single device it's a bit painful to maintain if you don't create separate user account for personal and job works.

I used to override the local .git/config for my personal projects while leaving the --global config for bitbucket.

But today I'll share a trick that will help you to handle this situation automatically! In order to do this your git version must be above 2.13. Let's check that first.

git -v
Enter fullscreen mode Exit fullscreen mode

My git version is 2.38.1. So this trick will work for me. You can continue following this guide if your git version is larger than 2.13.


Let's say you follow this file structure for your projects

~/
-- Personal/
---- Project A
---- Project B
-- Work/
---- Project A
---- Project B
Enter fullscreen mode Exit fullscreen mode

If you separately store you personal and work repositories then you are already a step ahead! If not then start by doing this first.

Once you have separated you repositories, let's look at the git config file:

cat ~/.gitconfig
Enter fullscreen mode Exit fullscreen mode

It may look like this if don't have anything but name and email

[user]
    name = user_name
    email = user@gmail.com
Enter fullscreen mode Exit fullscreen mode

Let's create two new files for personal and work profiles:

touch ~/.gitconfig_personal
Enter fullscreen mode Exit fullscreen mode
touch ~/.gitconfig_work
Enter fullscreen mode Exit fullscreen mode

and open them in your favorite text editor. In my case VS Code.

code ~/.gitconfig_personal
Enter fullscreen mode Exit fullscreen mode

Now copy the content of ~/.gitconfig and modify as needed. After that save the file. Do same for the other config file.

Once done, let's open the ~/.gitconfig file in VS Code and add necessary changes to the files.

[includeIf "gitdir:~/Personal/"]
  path = .gitconfig_personal
[includeIf "gitdir:~/Work/"]
  path = .gitconfig_work
Enter fullscreen mode Exit fullscreen mode

Above code will allow you to conditionally include configs based on the directory.

You still will be able to override this using git config for specific repository.

💖 💪 🙅 🚩
sabbirshouvo
Sabbir Hasan

Posted on January 4, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related