Configure different git accounts depending on project

Published on 09/03/2024

There are a lot of useful scenarios in which we could prefer using a different git identity depending on the repository we are working on. Some examples:

  • Different accounts for personal and work projects.
  • Clients request specific account for their project, a normal situation for a freelance.
  • Using a different account for every Git platform provider.

We can use gitconfig and the ifinclude option to avoid the possibility to do a mistake committing and pushing using a wrong git account for a particular repository.

gitconfig is the global configuration file of the local git installtion and we can find it in our home folder, ~/.gitconfig.

Thanks to the includeif property we can override the configuration of a repository by different criteria, for example using the folder path of the repository.

# content of ~/.gitconfig
[user]
  name = Batman
  email = batman@batman.inc

[includeIf "gitdir:~/path/to/cliente1/"]
  path = ~/path/to/cliente1/.gitconfig
[includeIf "gitdir:~/path/to/my-wonderful-project/"]
  path = ~/path/to/my-wonderful-project/.gitconfig
  

# content of ~/path/to/cliente1/.gitconfig
[user]
  name = Robin
  email = robin@batman.inc


# content of ~/path/to/my-wonderful-project/.gitconfig
[user]
  name = Bruce Wayne
  email = bruce@wayne.inc
  • Article is published under CC-BY 4.0
  • If not explicitly declared code snippets are published under MIT license