通过 Git IncludeIf
配置 自动在不同的项目中使用不同的 Git 账号
Git 允许你为不同的项目目录自动切换 Git 账户,无需手动更改 SSH Host。
1. 创建不同的 Git 配置文件
我们将在 ~/.gitconfig
中设置全局规则,并为个人和工作账户创建单独的 Git 配置。
全局 Git 配置 (~/.gitconfig
)
运行:
nano ~/.gitconfig
添加:
[user]
name = Default Name
email = default@example.com
[includeIf "gitdir:~/Projects/Personal/"]
path = ~/.gitconfig-personal
[includeIf "gitdir:~/Projects/Work/"]
path = ~/.gitconfig-work
这表示:
~/Projects/Personal/
下的所有仓库 自动使用 ~/.gitconfig-personal
~/Projects/Work/
下的所有仓库 自动使用 ~/.gitconfig-work
(注意:includeIf
行最后的 /
必须保留)
2. 配置个人账户 (~/.gitconfig-personal
)
nano ~/.gitconfig-personal
添加:
[user]
name = Personal Name
email = personal@example.com
[core]
sshCommand = "ssh -i ~/.ssh/id_rsa_personal"
3. 配置工作账户 (~/.gitconfig-work
)
nano ~/.gitconfig-work
添加:
[user]
name = Work Name
email = work@example.com
[core]
sshCommand = "ssh -i ~/.ssh/id_rsa_work"
4. 组织项目目录
确保项目放在对应的目录:
mkdir -p ~/Projects/Personal
mkdir -p ~/Projects/Work
然后:
# 克隆个人项目
cd ~/Projects/Personal
git clone git@github.com:personal-user/repo.git
# 克隆工作项目
cd ~/Projects/Work
git clone git@github.com:work-user/repo.git
效果
这样:
- 当你在
~/Projects/Personal/
目录工作时,Git 自动使用 个人账户 (id_rsa_personal
)
- 当你在
~/Projects/Work/
目录工作时,Git 自动使用 工作账户 (id_rsa_work
)