.git-credentials顺序导致git-push失效,如何共存两个凭证?
Git凭证文件行顺序导致push失效的原因及解决方法
问题原因
Git的凭证助手在查找匹配凭证时,是按.git-credentials文件从上到下的顺序匹配的,它会取第一个符合远程URL规则的凭证进行认证。如果你的仓库对应user2,但文件里第一个是user1的全局GitHub凭证,Git会错误用user1的凭证推送user2的仓库,导致认证失败;调换顺序后user2的凭证排在前面,能被优先匹配,所以可以正常push。
无需调换行顺序的解决方法
1. 精确指定凭证对应的仓库路径
修改.git-credentials文件,把凭证绑定到具体仓库而非整个github.com,Git会根据远程URL精确匹配,不受顺序影响:
https://user1:ghp_password1@github.com/user1/repo1.git https://user2:ghp_password2@github.com/user2/repo2.git
2. 给单个仓库指定专属用户名
进入需要特定凭证的仓库目录,执行以下命令,强制该仓库使用指定用户名,凭证助手会自动匹配对应凭证:
git config credential.https://github.com.username user2
3. 为不同仓库配置独立的凭证文件
分别给不同仓库指定单独的凭证存储文件,彻底避免冲突:
- 进入
user1的仓库,执行:git config credential.helper 'store --file ~/.git-credentials-user1' - 进入
user2的仓库,执行:git config credential.helper 'store --file ~/.git-credentials-user2'
之后各自仓库的凭证会存在对应文件里,互不干扰。
内容的提问来源于stack exchange,提问作者Sir Rubberduck
相关产品推荐
相关产品推荐

