Video in progress
At which levels are `git config` settings stored, and how do you automatically separate different emails and SSH keys for work and personal projects?
The main levels are system (/etc/gitconfig), global (~/.gitconfig) and local (.git/config); the lower level wins. For the work folder I attach a separate file with includeIf "gitdir:~/work/" and set user.email and core.sshCommand in it.
📖 Answer
To see which value comes from where:
git config --list --show-origin --show-scope | grep user
# global file:/Users/aziz/.gitconfig user.email=aziz@gmail.com
# local file:.git/config user.email=aziz@shop.uz
Running git config user.email by hand in every repo works, but you forget it on a fresh clone. The result is commits with a personal email landing in the company repo, which is a problem for audits and CLAs.
The automatic way:
# ~/.gitconfig
[user]
name = Aziz Karimov
email = aziz@gmail.com
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work
# ~/.gitconfig-work
[user]
email = aziz@shop.uz
signingkey = ~/.ssh/id_ed25519_work.pub
[core]
sshCommand = ssh -i ~/.ssh/id_ed25519_work -o IdentitiesOnly=yes
The / at the end of gitdir: matters: it means "this folder and everything inside it". In Git 2.36+ there is also the condition includeIf "hasconfig:remote.*.url:git@github.com:shop/**", which attaches by remote URL regardless of the folder.
Know that there are a few more levels: git config --worktree (specific to a worktree) and environment variables (GIT_AUTHOR_EMAIL, GIT_COMMITTER_EMAIL). These are used when committing as a bot in CI, and they override every file.
On the SSH side, the alternative is a Host github-work alias in ~/.ssh/config, but then you also have to change the remote URL. includeIf is usually more convenient.
Sign up to mark studied questions and save your progress.