Multiple Git Profiles on a Single Machine

Multiple Git Profiles on a Single Machine

Firstly, I would like to apologise to my thousands of readers that follow my RSS feed, for being absent for so long. It was one of those strange things of the longer I left it, the stranger it felt to even attempt to make a return. The same horde of readers may have also noticed my absence from Mastodon as of late too - same thing. I'm slowly trying to make my return!

With that out of the way, on to the main purpose of this post. You probably already know how to do this, but it wouldn't hurt as a reminder for myself.

I needed to use my personal git account on my work machine to be able to push something back to a Codeberg repo. While I'm aware you can specify this per repo, I thought it would be useful to be able to have this setup on a more permanent basis, especially as I find myself interacting with git far more in my new role.

The first part of the solution was from https://deepsource.io/blog/managing-different-git-profiles/

Git offers a much more flexible way of specifying conditional config files based on your current directory — if you use a different directory for all your work repos (let’s say ~/work/), then you can specify the following in your ~/.gitconfig to automatically use your work credentials inside them:

As I already have my workflow setup (see what I did there, genius!), I just needed to reverse this for my personal folders.

So, in my .gitconfig file, I added the following:

[includeIf "gitdir:~/Personal/Repos"]
	path = ~/git-personal.conf

In the git-personal.conf

[user]
	name = Your Name
	email = your.name@domain.com

The next step was to specify a particular key for SSH. I found info on how to do this here: https://dev.to/web3coach/how-to-configure-a-local-git-repository-to-use-a-specific-ssh-key-4aml

This can be achieved by adding [core] and using sshCommand in your git-personal.conf file. So it should look like this:

[user]
	name = Your Name
	email = your.name@domain.com
[core]
	sshCommand = "ssh -i ~/.ssh/id_codeberg"

Now, whenever I do anything inside the ~/Personal/Repos directory, I know it's only ever going to use that git config, and that key.

I hope someone else finds this helpful.

Show Comments