luisduenas

light mode

Handling multiple Github accounts in the same machine

September 08, 2023

test

Sometimes you find yourself in need to have multiple Github accounts in the same machine, for example, you can be working with different clients and instead of using you personal account you are asked to use an account provided by them.

This can be an issue that you would see reflected in your commits, the solution to this is to add a different git user depending on the project we are working, that way you will always have the correct commit history.

This can sound trivial but is very easy to achieve, I will show you the way I do it, I'm sure there are other ways but this one is very simple and I've worked like this for a long time without any issue.

First things first, in order for this to work correctly you'll need to have some order in your directories, this will make it easier.

In my case I have a directory called work, and inside them I have one directory for every client I work with, and inside those directories you will find the repositories for each client.

Now that you have your projects in order, we need to add a global gitconfig to add some validations, this will depend on the OS that you are using, in my case, this file is located in /etc/gitconfig.

Inside the gitconfig file, I have my default user

[user]
	email = hello@luisduenas.dev
	name = luisduenas

That's my default git configuration, no big deal, let's add a validation for a specific directory.

Below my default user, I added a validation for one of the clients I work with:

[includeIf "gitdir:~/work/octahedroid/"]
    path = ~/work/octahedroid/.gitconfig

So, what's going on here?

  • includeIf "gitdir:~/work/octahedroid/": This is telling git to include this configuration when the repository is inside ~/work/octahedroid/. As you can assume, inside this directory I have a bunch of repos from Octahedroid, I want a different user in my commits for this repo.
  • path = ~/work/octahedroid/.gitconfig: This is where the default configuration for Octahedroid is defined, in that file we can add a different user and a different name.

After updating the /etc/gitconfig file, we are going to add a new .gitconfig file in ~/work/octahedroid/.

In my case, that file looks like this:

[user]
    name = luisduenas
    email = luisduenas@octahedroid.com

And that's it!, next time you add a commit in any repo inside ~/work/octahedroid/ git will read the config specified in the .gitconfig file in that directory and you will have a different user without any other effort.

You can have as many conditions as you want in the global config file.


Profile picture

luisduenas / web developer
Learning to code since 2016.