git 我可以在 .gitconfig 中为自己指定多个用户吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4220416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I specify multiple users for myself in .gitconfig?
提问by Brock Boland
In my ~/.gitconfig
, I list my personal email address under [user]
, since that's what I want to use for Github repos.
在我的 中~/.gitconfig
,我在 下列出了我的个人电子邮件地址[user]
,因为这是我想用于 Github 存储库的地址。
But, I've recently started using git for work, too. My company's git repo allows me to commit, but when it sends out announcements of new changesets, it says they are from Anonymous because it doesn't recognize the email address in my .gitconfig
- at least, that's my theory.
但是,我最近也开始在工作中使用 git。我公司的 git repo 允许我提交,但是当它发出新变更集的公告时,它说它们来自 Anonymous,因为它无法识别我的电子邮件地址.gitconfig
- 至少,这是我的理论。
Is it possible to specify multiple [user]
definitions in .gitconfig
? Or is there some other way to override the default .gitconfig
for a certain directory? In my case, I check out all work code in ~/worksrc/
- is there a way to specify a .gitconfig
for only that directory (and its subdirectories)?
是否可以在 中指定多个[user]
定义.gitconfig
?或者是否有其他方法可以覆盖.gitconfig
某个目录的默认值?就我而言,我检查了所有工作代码~/worksrc/
- 有没有办法.gitconfig
只为该目录(及其子目录)指定一个?
回答by discomurray
You can configure an individual repo to use a specific user / email address which overrides the global configuration. From the root of the repo, run
您可以将单个存储库配置为使用覆盖全局配置的特定用户/电子邮件地址。从 repo 的根目录,运行
git config user.name "Your Name Here"
git config user.email [email protected]
whereas the default user / email is configured in your ~/.gitconfig
而默认用户/电子邮件在您的 ~/.gitconfig 中配置
git config --global user.name "Your Name Here"
git config --global user.email [email protected]
回答by Tomá? Janou?ek
Since git 2.13, it is possible to solve this using newly introduced Conditional includes.
从 git 2.13 开始,可以使用新引入的Conditional includes来解决这个问题。
An example:
一个例子:
Global config ~/.gitconfig
全局配置~/.gitconfig
[user]
name = John Doe
email = [email protected]
[includeIf "gitdir:~/work/"]
path = ~/work/.gitconfig
Work specific config ~/work/.gitconfig
工作特定配置~/work/.gitconfig
[user]
email = [email protected]
回答by Rahul Prasad
Or you can add following information in your local .git/config
file
或者您可以在本地.git/config
文件中添加以下信息
[user]
name = Your Name
email = [email protected]
回答by Kaleem Ullah
One command github accounts switch
一个命令github账户切换
This solution takes the form of a single git alias. Once executed, the current project user will be attached to another account
此解决方案采用单个 git 别名的形式。一旦执行,当前项目用户将附加到另一个帐户
Generate ssh keys
生成 ssh 密钥
ssh-keygen -t rsa -C "[email protected]" -f '/Users/arnaudrinquin/.ssh/id_rsa'
[...]
ssh-keygen -t rsa -C "[email protected]" -f '/Users/arnaudrinquin/.ssh/id_rsa_pro'
Link them to your GitHub / Bitbucket accounts
将它们链接到您的 GitHub / Bitbucket 帐户
- copy default public key
pbcopy < ~/.ssh/id_rsa.pub
- login to your GitHub acount
- paste the key in the
add SSH key
github page - copy other public key
pbcopy < ~/.ssh/id_rsa_pro.pub
- repeat and adapt steps 2 to 4 for every other account
- 复制默认公钥
pbcopy < ~/.ssh/id_rsa.pub
- 登录到您的 GitHub 帐户
- 将密钥粘贴到
add SSH key
github 页面中 - 复制其他公钥
pbcopy < ~/.ssh/id_rsa_pro.pub
- 为每个其他帐户重复并调整步骤 2 到 4
Step 1. Automatic ssh key switching.
步骤 1. 自动 ssh 密钥切换。
We can configure ssh
to send a use a specific encryption key depending on the host
. The nice thing is that you can have several aliases for the same hostname
.
我们可以配置ssh
为根据host
. 好消息是您可以为同一个hostname
.
See this example ~/.ssh/config
file:
请参阅此示例~/.ssh/config
文件:
# Default GitHub
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
# Professional github alias
Host github_pro
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_pro
git remote configuration
git远程配置
You can now use these aliases in the git remotes by changing [email protected]
by git@github_pro
.
现在,您可以通过改变使用git的遥控器这些别名[email protected]
通过git@github_pro
。
You can either change your existing projects remotes (using something like git remote set-url origin git@github_pro:foo/bar.git
) or adapt them directly when cloning them.
您可以更改现有项目的遥控器(使用类似git remote set-url origin git@github_pro:foo/bar.git
)或在克隆它们时直接调整它们。
git clone [email protected]:ArnaudRinquin/atom-zentabs.git
using alias, it become:
使用别名,它变成:
git clone git@github_pro:ArnaudRinquin/atom-zentabs.git
git clone git@github_pro:ArnaudRinquin/atom-zentabs.git
Step 2. Changing git user.email
步骤 2. 更改 git user.email
Git config settings can be global or per project. In our case, we want a per project settings. It is very easy to change it:
Git 配置设置可以是全局的,也可以是每个项目的。在我们的例子中,我们需要一个每个项目的设置。更改它非常容易:
git config user.email '[email protected]'
While this is easy, it takes way to long for the developers we are. We can write a very simple git alias for that.
虽然这很容易,但对于我们这样的开发人员来说,这需要很长时间。我们可以为此编写一个非常简单的 git 别名。
We are going to add it to the ~/.gitconfig
file.
我们将把它添加到~/.gitconfig
文件中。
[user]
name = Arnaud Rinquin
email = [email protected]
...
[alias]
setpromail = "config user.email '[email protected]'"
Then, all we have to do is git setpromail
to have our email changed for this project only.
然后,我们所要做的就是git setpromail
仅为该项目更改我们的电子邮件。
Step 3. One command switch please?!
第 3 步。请一个命令开关?!
Wouldn't it be nice to switch from default account to a specified one with a single parameter-less command? This is definitely possible. This command will have two steps:
使用单个无参数命令从默认帐户切换到指定帐户不是很好吗?这绝对是可能的。此命令将有两个步骤:
- change current project remotes to the chosen aliases
- change current project user.email config
- 将当前项目遥控器更改为所选别名
- 更改当前项目 user.email 配置
We already have a one command solution for the second step, but the first one is way harder. One command remote host change
我们已经有了第二步的单命令解决方案,但第一步要困难得多。一命令远程主机更改
Here comes the solution in the form of another git alias command to add to your ~/.gitconfig
:
这是另一个 git alias 命令形式的解决方案,可添加到您的~/.gitconfig
:
[alias]
changeremotehost = !sh -c \"git remote -v | grep '.*fetch' | sed s/..fetch.// | sed s/// | xargs git remote set-url\"
This allows changing all remotes from one host to another (the alias). See the example:
这允许将所有遥控器从一台主机更改为另一台(别名)。看例子:
$ > git remote -v
origin [email protected]:ArnaudRinquin/arnaudrinquin.github.io.git (fetch)
origin [email protected]:ArnaudRinquin/arnaudrinquin.github.io.git (push)
$ > git changeremotehost github.com github_pro
$ > git remote -v
origin git@github_pro:ArnaudRinquin/arnaudrinquin.github.io.git (fetch)
origin git@github_pro:ArnaudRinquin/arnaudrinquin.github.io.git (push)
Combine them all
将它们全部结合起来
We now just have to combine the two commands into one, this is quite easy. See how I also integrate bitbucket host switching.
我们现在只需要将这两个命令合二为一,这很容易。看看我还如何集成 bitbucket 主机切换。
[alias]
changeremotehost = !sh -c \"git remote -v | grep '.*fetch' | sed s/..fetch.// | sed s/// | xargs git remote set-url\"
setpromail = "config user.email '[email protected]'"
gopro = !sh -c \"git changeremotehost github.com github_pro && git changeremotehost bitbucket.com bitbucket_pro && git setpromail\"
回答by Saucier
After getting some inspiration from Orr Sella's blog postI wrote a pre-commit hook (resides in ~/.git/templates/hooks
) which would set specific usernames and e-mail addresses based on the information inside a local repositorie's ./.git/config
:
在从Orr Sella 的博客文章中获得一些灵感后,我编写了一个预提交钩子(位于~/.git/templates/hooks
),它会根据本地存储库中的信息设置特定的用户名和电子邮件地址./.git/config
:
You have to place the path to the template directory into your ~/.gitconfig
:
您必须将模板目录的路径放入您的~/.gitconfig
:
[init]
templatedir = ~/.git/templates
Then each git init
or git clone
will pick up that hook and will apply the user data during the next git commit
. If you want to apply the hook to already exisiting repos then just run a git init
inside the repo in order to reinitialize it.
然后每个git init
orgit clone
将拿起那个钩子并在下一个期间应用用户数据git commit
。如果您想将钩子应用于已经存在的存储库,那么只需git init
在存储库中运行 a即可重新初始化它。
Here is the hook I came up with (it still needs some polishing - suggestions are welcome). Save it either as
这是我想出的钩子(它仍然需要一些改进 - 欢迎提出建议)。将其另存为
~/.git/templates/hooks/pre_commit
or
或者
~/.git/templates/hooks/post-checkout
and make sure it is executable: chmod +x ./post-checkout || chmod +x ./pre_commit
并确保它是可执行的: chmod +x ./post-checkout || chmod +x ./pre_commit
#!/usr/bin/env bash
# -------- USER CONFIG
# Patterns to match a repo's "remote.origin.url" - beginning portion of the hostname
git_remotes[0]="Github"
git_remotes[1]="Gitlab"
# Adjust names and e-mail addresses
local_id_0[0]="my_name_0"
local_id_0[1]="my_email_0"
local_id_1[0]="my_name_1"
local_id_1[1]="my_email_1"
local_fallback_id[0]="${local_id_0[0]}"
local_fallback_id[1]="${local_id_0[1]}"
# -------- FUNCTIONS
setIdentity()
{
local current_id local_id
current_id[0]="$(git config --get --local user.name)"
current_id[1]="$(git config --get --local user.email)"
local_id=("$@")
if [[ "${current_id[0]}" == "${local_id[0]}" &&
"${current_id[1]}" == "${local_id[1]}" ]]; then
printf " Local identity is:\n"
printf "? User: %s\n? Mail: %s\n\n" "${current_id[@]}"
else
printf "? User: %s\n? Mail: %s\n\n" "${local_id[@]}"
git config --local user.name "${local_id[0]}"
git config --local user.email "${local_id[1]}"
fi
return 0
}
# -------- IMPLEMENTATION
current_remote_url="$(git config --get --local remote.origin.url)"
if [[ "$current_remote_url" ]]; then
for service in "${git_remotes[@]}"; do
# Disable case sensitivity for regex matching
shopt -s nocasematch
if [[ "$current_remote_url" =~ $service ]]; then
case "$service" in
"${git_remotes[0]}" )
printf "\n?? An Intermission\n? %s repository found." "${git_remotes[0]}"
setIdentity "${local_id_0[@]}"
exit 0
;;
"${git_remotes[1]}" )
printf "\n?? An Intermission\n? %s repository found." "${git_remotes[1]}"
setIdentity "${local_id_1[@]}"
exit 0
;;
* )
printf "\n? pre-commit hook: unknown error\n? Quitting.\n"
exit 1
;;
esac
fi
done
else
printf "\n?? An Intermission\n? No remote repository set. Using local fallback identity:\n"
printf "? User: %s\n? Mail: %s\n\n" "${local_fallback_id[@]}"
# Get the user's attention for a second
sleep 1
git config --local user.name "${local_fallback_id[0]}"
git config --local user.email "${local_fallback_id[1]}"
fi
exit 0
EDIT:
编辑:
So I rewrote the hook as a hook and command in Python. Additionally it's possible to call the script as a Git command (git passport
), too. Also it's possible to define an arbitrary number of IDs inside a configfile (~/.gitpassport
) which are selectable on a prompt. You can find the project at github.com: git-passport - A Git command and hook written in Python to manage multiple Git accounts / user identities.
所以我将钩子重写为 Python 中的钩子和命令。此外,也可以将脚本作为 Git 命令 ( git passport
)调用。还可以在配置文件 ( ~/.gitpassport
) 中定义任意数量的 ID,这些 ID可在提示中选择。您可以在 github.com 上找到该项目:git-passport - 用 Python 编写的用于管理多个 Git 帐户/用户身份的 Git 命令和钩子。
回答by John
If you do not want to have a default email address (email address links to a github user), you can configure that you want to be asked. How you can do that depends on the version of git you use, see below.
如果您不想拥有默认电子邮件地址(指向 github 用户的电子邮件地址链接),您可以配置您希望被询问。如何做到这一点取决于您使用的 git 版本,请参见下文。
The (intended) drawback is that you have to configure your email address (and your name) once for every repository. So, you cannot forget to do it.
(预期的)缺点是您必须为每个存储库配置一次您的电子邮件地址(和您的姓名)。所以,你不能忘记去做。
Version < 2.7.0
版本 < 2.7.0
[user]
name = Your name
email = "(none)"
in your global configuration ~/.gitconfig
as stated in a comment by Dan Aloni in Orr Sella's blog post. When trying to do the first commit in a repository, git fails with the nice message:
在您的全局配置中,~/.gitconfig
如 Dan Aloni 在Orr Sella 的博客文章中的评论中所述。尝试在存储库中进行第一次提交时,git 失败并显示好消息:
*** Please tell me who you are.
Run
git config --global user.email "[email protected]"
git config --global user.name "Your Name"
to set your account's default identity.
Omit --global to set the identity only in this repository.
fatal: unable to auto-detect email address (got '(none)')
The name is taken from the global config when the email address is set locally (the message is not perfectly accurate).
当电子邮件地址在本地设置时,该名称取自全局配置(消息并不完全准确)。
2.7.0 ≤ Version < 2.8.0
2.7.0 ≤ 版本 < 2.8.0
The behaviour in versions < 2.7.0 was not intended and fixed with 2.7.0. You can still use a pre-commit hook as described in Orr Sella's blog post. This solution works also for other versions, but the other solutions not for this version.
版本 < 2.7.0 中的行为不是有意的,而是在 2.7.0 中修复的。您仍然可以使用预提交挂钩,如Orr Sella 的博客文章 中所述。此解决方案也适用于其他版本,但其他解决方案不适用于此版本。
Version ≥ 2.8.0
版本 ≥ 2.8.0
Dan Aloni addedan option to achieve that behaviour (see release notes). Use it with:
Dan Aloni 添加了一个选项来实现该行为(请参阅发行说明)。使用它:
[user]
useConfigOnly = true
To make it work you may not give a name or email address in the global config. Then, at the first commit, you get an error message
为了使其工作,您可能不会在全局配置中提供姓名或电子邮件地址。然后,在第一次提交时,您会收到一条错误消息
fatal: user.useConfigOnly set but no name given
So the message is not very instructive, but since you set the option explicitly, you should know what to do. In contrast to the solution of versions < 2.7.0, you always have to set both name and email manually.
因此该消息不是很有指导意义,但由于您明确设置了该选项,因此您应该知道该怎么做。与版本 < 2.7.0 的解决方案相比,您始终必须手动设置姓名和电子邮件。
回答by hIpPy
With conditional includesin Git 2.13, it is now possible to have multiple user/email coexist on one machine with little work.
使用Git 2.13 中的条件包含,现在可以在一台机器上共存多个用户/电子邮件,而只需很少的工作。
user.gitconfig
has my personal name and email. work-user.gitconfig
has my work name and email. Both files are at ~
path.
user.gitconfig
有我的个人姓名和电子邮件。work-user.gitconfig
有我的工作名称和电子邮件。两个文件都在~
路径中。
So my personal name/email applies by default. For c:/work/
dir, my work name/email is applied. For c:/work/github/
dir, my personal name/email is applied. This works as the last setting gets applied.
所以我的个人姓名/电子邮件默认适用。对于c:/work/
dir,应用我的工作名称/电子邮件。对于c:/work/github/
dir,应用我的个人姓名/电子邮件。这在应用最后一个设置时起作用。
# ~/.gitconfig
[include]
path = user.gitconfig
[includeIf "gitdir/i:c:/work/"]
path = work-user.gitconfig
[includeIf "gitdir/i:c:/work/github/"]
path = user.gitconfig
gitdir
is case-sensitive and gitdir/i
is case-insensitive.
gitdir
区分大小写和gitdir/i
不区分大小写。
"gitdir/i:github/"
would apply the conditional include for any directory with github
in its path.
"gitdir/i:github/"
会将条件包含应用于github
其路径中的任何目录。
回答by Rob W
Another option to get git
to work with multiple names / emails is by aliasing git
and using the -c
flag to override the global and repository-specific config.
git
使用多个名称/电子邮件的
另一种选择是通过别名git
和使用-c
标志来覆盖全局和特定于存储库的配置。
For example, by defining an alias:
例如,通过定义别名:
alias git='/usr/bin/git -c user.name="Your name" -c user.email="[email protected]"'
To see whether it works, simply type git config user.email
:
要查看它是否有效,只需键入git config user.email
:
$ git config user.email
[email protected]
Instead of an alias, you could also put a custom git
executable within your $PATH
.
除了别名,您还可以将自定义git
可执行文件放在$PATH
.
#!/bin/sh
/usr/bin/git -c user.name="Your name" -c user.email="[email protected]" "$@"
An advantage of these method over a repository-specific .git/config
is that it applies to every git
repository when the custom git
program is active. In this way, you can easily switch between users/names without modifying any (shared) configuration.
这些方法相对于特定于存储库的优势.git/config
在于,git
当自定义git
程序处于活动状态时,它适用于每个存储库。通过这种方式,您可以轻松地在用户/名称之间切换,而无需修改任何(共享)配置。
回答by codesnik
git aliases (and sections in git configs) to the rescue!
git 别名(以及 git configs 中的部分)来救援!
add an alias (from command line):
添加别名(从命令行):
git config --global alias.identity '! git config user.name "$(git config user..name)"; git config user.email "$(git config user..email)"; :'
then, set, for example
然后,设置,例如
git config --global user.github.name "your github username"
git config --global user.github.email [email protected]
and in a new or cloned repo you can run this command:
在新的或克隆的 repo 中,您可以运行以下命令:
git identity github
This solution isn't automatic, but unsetting user and email in your global ~/.gitconfig
and setting user.useConfigOnly
to true
would force git to remind you to set them manually in each new or cloned repo.
该解决方案是不是自动的,但解封用户和电子邮件在全球~/.gitconfig
和设置user.useConfigOnly
,以true
将迫使混帐提醒你手动设置在每一个新的或克隆的回购协议。
git config --global --unset user.name
git config --global --unset user.email
git config --global user.useConfigOnly true
回答by Mauricio Gracia Gutierrez
Here are the complete steps after reading many answers here
以下是阅读此处的许多答案后的完整步骤
How to set up Multiple SSH Keys settings for different github account
如何为不同的 github 帐户设置多个 SSH 密钥设置
You might want to start checking your currently saved keys
您可能想要开始检查当前保存的密钥
$ ssh-add -l
If you decide to delete all cached keys before (optional, carefull about this)
如果您之前决定删除所有缓存的键(可选,请注意这一点)
$ ssh-add -D
Then you can create a ssh pub/priv key linked to each email/account that you wish/need to use
然后您可以创建一个链接到您希望/需要使用的每个电子邮件/帐户的 ssh pub/priv 密钥
$ cd ~/.ssh
$ ssh-keygen -t rsa -C "[email protected]" <-- save it as "id_rsa_work"
$ ssh-keygen -t rsa -C "[email protected]" <-- save it as "id_rsa_pers"
After performing this commands you will have the following files created
执行此命令后,您将创建以下文件
~/.ssh/id_rsa_work
~/.ssh/id_rsa_work.pub
~/.ssh/id_rsa_pers
~/.ssh/id_rsa_pers.pub
Make sure authentication agentis running
确保身份验证代理正在运行
$ eval `ssh-agent -s`
Add the generated keys as following (from the ~/.ssh folder)
添加生成的密钥如下(来自 ~/.ssh 文件夹)
$ ssh-add id_rsa_work
$ ssh-add id_rsa_pers
Now you can check your saved keys again
现在您可以再次检查您保存的密钥
$ ssh-add -l
Now you needto add the generated public keys to your github/bickbuket server Acces Keys
现在您需要将生成的公钥添加到您的 github/bickbuket 服务器 Access Keys
Clone each of the repos to different folders
将每个 repos 克隆到不同的文件夹
Go to the folder where the user workwill work and execute this
转到用户工作所在的文件夹并执行此操作
$ git config user.name "Working Hard"
$ git config user.email "[email protected]"
Just to see what this does check the contents of the ".git/config"
只是为了看看这会检查“.git/config”的内容
Go to the folder where the user perswill work and execute this
进入该文件夹,其中用户个人将工作和执行这个
$ git config user.name "Personal Account"
$ git config user.email "[email protected]"
Just to see what this does check the contents of the ".git/config"
只是为了看看这会检查“.git/config”的内容
After all this you will be able to commit your personal and work code by just switching between those two folders
毕竟,您只需在这两个文件夹之间切换即可提交您的个人和工作代码