Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch git email based on host?

I have accounts in three different Git service providers - GitHub, GitLab and BitBucket. I want to ensure that my commits are signed via SSH in all of the mentioned providers, which is not possible since I have assigned a GitLab email at the moment, and all of my accounts use unique emails. This only verifies signed commits for GitLab successfully. How do I make it so that GitHub/BitBucket repositories will be assigned to their respective email?

Haven't found anything online that deals with this. There is a "gitdir" method, but I am not looking for this. I am expecting that Git understands what host I am using (if on GitHub, use [email protected], if on GitLab, use [email protected] and so on), and based on that, assign emails.


1 Answers

Unfortunately, Git config does not support conditionals directly, but includes other config files. I was able to resolve my issue by using hasconfig:remote.*.url condition for includeIf. You may remove the email variable under [user] block - this is your global email. Create four new blocks for the same (two for each remote - one for HTTPS one for SSH). Here's an example of how my .gitconfig file looks like:

.gitconfig

[user]
  name = <Your name>

[includeIf "hasconfig:remote.*.url:[email protected]:**/**"]
    path = github

[includeIf "hasconfig:remote.*.url:https://github.com/**/**"]
    path = github

[includeIf "hasconfig:remote.*.url:[email protected]:**/**"]
    path = gitlab

[includeIf "hasconfig:remote.*.url:https://gitlab.com/**/**"]
    path = gitlab

[init]
  defaultBranch = main

[core]
  editor = vim 

[color]
  ui = auto

[gpg]
  format = ssh 

[commit]
  gpgsign = true

Now create config files for the respective remotes. I've created .github, and .gitlab in the same directory as .gitconfig:

.github

[user]
  email = [email protected]
  signingkey = ~/.ssh/github-key.pub

.gitlab

[user]
  email = [email protected]
  signingkey = ~/.ssh/gitlab-key.pub

Edit 1: Initially, there were three different configs, one for GitHub, GitLab and Bitbucket, I've removed Bitbucket for simplicity.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!