场景

个人项目与工作项目需要使用不同的 Git 身份和 SSH 密钥。可以让本地电脑默认使用个人配置,并为指定工作目录自动加载另一套配置。

以下域名、邮箱、用户名和路径均为占位示例,请按实际环境替换。

个人 git 配置:

# ~/.gitconfig
[user]
	name = Personal User
	email = personal@example.com
 
[core]
	editor = code --wait
 
[https]
	proxy = 127.0.0.1:7890
 
[http]
	proxy = 127.0.0.1:7890
	sslBackend = schannel
 
[includeIf "gitdir/i:C:/Workspace/company/**"]
  path = ~/.gitconfig-work
 

工作 git 配置

# ~/.gitconfig-work
[user]
  name = Work User
  email = work@example.com
 

ssh 配置:

~/.ssh/config:

Host gitlab-work
  HostName gitlab.example.com
  User git
  Port 22
  IdentityFile ~/.ssh/id_ed25519_gitlab_work
  IdentitiesOnly yes
  PreferredAuthentications publickey

如果全局代理会影响工作 GitLab,可通过 git@gitlab-work:group/repo.git 形式的远端地址明确使用上述 SSH 配置。