Git Push 失败常见原因排查
Git push 失败是开发中常见问题,通常由权限、配置或内容冲突引起。以下是 8 种常见原因,每种都包括原因分析、如何识别(通过错误消息)和解决步骤。排查时,建议依次检查这些点,确保问题高效解决。
1. 权限不足 (Permission Denied)
- 原因:用户对远程仓库没有写入权限,常见于 SSH 密钥无效或账户权限不足。
- 识别:错误消息如
remote: Permission to user/repo.git denied to user.或fatal: unable to access 'https://github.com/user/repo.git/': The requested URL returned error: 403。 - 解决步骤:
- 检查 SSH 密钥:运行
ssh -T [email protected]测试连接。 - 确保 Git 配置正确:使用
git config --global user.name和git config --global user.email验证账户。 - 如果使用 HTTPS,更新凭证:运行
git credential-manager reject(Windows)或git config --global credential.helper cache(Linux/macOS)重新输入密码。 - 联系仓库管理员添加权限。
- 检查 SSH 密钥:运行
2. 分支保护 (Protected Branch)
- 原因:远程分支(如
main或master)被设置为保护分支,禁止直接推送,常见于 GitHub 或 GitLab。 - 识别:错误消息如
remote: error: GH006: Protected branch update failed for refs/heads/main.或remote: You are not allowed to force push code to a protected branch on this project.。 - 解决步骤:
- 检查分支保护设置:在仓库的 "Settings" > "Branches" 中查看。
- 改用 Pull Request:推送到一个新分支,然后创建 PR 合并。
- 临时禁用保护(需管理员权限),或使用
git push --force-with-lease(谨慎使用)。
3. 冲突未解决 (Merge Conflicts)
- 原因:本地提交与远程分支有冲突,Git 要求先解决冲突再推送。
- 识别:错误消息如
! [rejected] main -> main (fetch first)或error: failed to push some refs to 'origin',提示先运行git pull。 - 解决步骤:
- 拉取远程更新:运行
git pull origin <branch>(将<branch>替换为实际分支名)。 - 手动解决冲突:编辑文件,Git 会标记冲突部分(如
<<<<<<< HEAD)。 - 添加并提交解决后的文件:
git add .后git commit -m "Resolved conflicts"。 - 重新推送:
git push origin <branch>。
- 拉取远程更新:运行

