按目录管理GitHub权限的术语是什么?如何配置多Git仓库不同凭据?
为不同Git仓库配置独立用户信息与凭据
一、设置仓库专属用户信息
Git允许为单个仓库单独配置用户名和邮箱,覆盖全局配置:
- 进入
~/go/foo目录,执行以下命令设置该仓库专属的用户信息:git config user.name "Fred" git config user.email "fred@company.com" - 进入
~/go/bar目录,执行以下命令设置对应仓库的用户信息:git config user.name "Fred" git config user.email "fredz@company2.com"
执行git config --list可以验证当前仓库的配置,确认user.email是对应邮箱即可。
二、配置独立推送凭据
要让不同仓库用不同账号的凭据推送,有两种实用方式:
方式1:修改仓库远程URL嵌入用户名
直接把对应账号的用户名嵌入仓库的远程地址,Git推送时会自动匹配该账号的凭据:
- 针对
~/go/foo仓库,修改origin地址:git remote set-url origin https://fred@company.com@github.com/company1/foo.git - 针对
~/go/bar仓库,修改origin地址:git remote set-url origin https://fredz@company2.com@github.com/company2/bar.git
第一次推送时输入对应账号的GitHub个人访问令牌(PAT)或密码,Git的凭据助手会自动保存,后续推送无需重复输入。
方式2:按路径配置凭据存储
如果不想修改远程URL,可以通过全局Git配置按仓库路径区分凭据存储:
- 编辑全局配置文件
~/.gitconfig,添加以下内容:[credential "https://github.com"] helper = store --file ~/.git-credentials-company1 [credential "https://github.com/company2"] helper = store --file ~/.git-credentials-company2 - 创建两个凭据文件,分别写入对应账号的凭据信息:
~/.git-credentials-company1内容:https://fred@company.com:你的PAT令牌@github.com~/.git-credentials-company2内容:https://fredz@company2.com:你的PAT令牌@github.com
- 设置文件权限为只读,避免泄露:
chmod 600 ~/.git-credentials-*
内容的提问来源于stack exchange,提问作者tomcam
相关产品推荐
相关产品推荐

