如果您有多个 git 配置文件(如工作配置文件、个人配置文件等)并在同一台电脑上使用,在不同配置文件间切换会很累,有时甚至会冒着推送到错误账户的风险。通过为不同目录设置不同的 git 配置文件, .gitconfig
文件本身就能缓解这些问题。
在下面的说明中,我将设置 3 个配置文件:
- personal
- party
- guild
步骤 1:创建目录
创建目录,为每个配置文件存储代码。
~/Documents/party ~/Documents/guild
步骤 2:创建自定义 git 配置文件
每个自定义 git 配置文件都存储了该配置文件的特定信息。
~/Documents/personal/.gitconfig-personal
[user]
email = myname@gmail.com
~/Documents/party/.gitconfig-party
[user]
email = myname@myparty.com
~/Documents/guild/.gitconfig-guild
[user]
email = myname@myguild.com
步骤 3:更新全局 git 配置文件
对于 Mac, .gitconfig
文件可在 /Users/<account>/
目录中找到。如果还不存在,请在此处创建。您的 .gitconfig
文件应如下所示
[includeIf "gitdir:~/Documents/personal/"]
path = ~/Documents/personal/.gitconfig-personal
[includeIf "gitdir:~/Documents/party/"]
path = ~/Documents/party/.gitconfig-party
[includeIf "gitdir:~/Documents/guild/"]
path = ~/Documents/guild/.gitconfig-guild
它的工作原理就像编码 中的开关,首先检查你所在的文件夹,然后读取相应配置文件的值。
其他选择
您也可以在 [includeIf]
之外设置默认配置文件,例如,使用 [include]
将 personal
设置为默认配置文件。
[include]
path = ~/Documents/personal/.gitconfig-personal
[includeIf "gitdir:~/Documents/party/"]
path = ~/Documents/party/.gitconfig-party
[includeIf "gitdir:~/Documents/guild/"]
path = ~/Documents/guild/.gitconfig-guild
或者不使用单独的包含文件。
[user]
email = myname@gmail.com
[includeIf "gitdir:~/Documents/party/"]
path = ~/Documents/party/.gitconfig-party
[includeIf "gitdir:~/Documents/guild/"]
path = ~/Documents/guild/.gitconfig-guild
步骤 4:测试
从终端进入之前创建的其中一个目录并创建一个文件夹,然后进入该文件夹并检查以下值
cd ~/Documents/party/
mkdir temp
cd temp
git config --get user.email
返回值应为
myname@myparty.com
Bonus
在上例中,我只在自定义 git 配置文件中设置了一个变量,而实际上我们可以根据需要设置多个变量。
[user]
email = myname@myparty.com
name = wwang[core]
sshCommand = "ssh -i ~/.ssh/party_github_key"
希望这篇文章对你有用,并欢迎你提出意见或反馈。祝您编码愉快!