# Git 错误模式
常见的 Git 错误及其诊断与解决方案。
## 推送/拉取错误
### 推送失败:被拒绝 (rejected)
! [rejected] main -> main (non-fast-forward)
error: failed to push some refs to 'origin'
**原因**:
1. 远程仓库有你本地没有的提交
2. 需要强制推送(历史记录被重写)
3. 分支保护规则
**解决方案**:
bash
# 选项 1: 先拉取并合并(最安全)
git pull origin main
git push origin main
# 选项 2: 使用变基 (rebase) 拉取
git pull --rebase origin main
git push origin main
# 选项 3: 强制推送(小心 - 会覆盖远程)
# 仅在你故意重写历史时使用
git push --force-with-lease origin main
---
### 远程包含你本地没有的工作
hint: Updates were rejected because the remote contains work that you do not have locally.
**同上** - 先拉取,再推送。
bash
# 标准工作流
git fetch origin
git merge origin/main # 或者: git rebase origin/main
git push
---
### 权限被拒绝 (publickey)
Permission denied (publickey).
fatal: Could not read from remote repository.
**原因**:
1. SSH 密钥未添加到代理
2. SSH 密钥未添加到 GitHub/GitLab
3. SSH 密钥错误
4. 使用了 HTTPS URL 而非 SSH
**诊断**:
bash
# 测试 SSH 连接
ssh -T
[email protected]
ssh -vT
[email protected] # 详细调试模式
# 检查已加载的密钥
ssh-add -l
**解决方案**:
bash
# 将 SSH 密钥添加到代理
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519 # 或你的密钥文件
# 如有需要,生成新密钥
ssh-keygen -t ed25519 -C "
[email protected]"
# 将公钥复制到 GitHub/GitLab
cat ~/.ssh/id_ed25519.pub
# 然后在 GitHub 设置 -> SSH Keys 中添加
# 或者使用 HTTPS 代替 SSH
git remote set-url origin https://github.com/user/repo.git
---
### 身份验证失败
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/...'
**原因**:
1. 凭据错误
2. 密码验证已禁用(GitHub)
3. 令牌过期
**解决方案**:
bash
# 使用个人访问令牌 (PAT) 代替密码
# 生成地址: GitHub -> Settings -> Developer settings -> Personal access tokens
# 更新存储的凭据
git credential reject
protocol=https
host=github.com
# 按两次回车
# 或者使用凭据助手
git config --global credential.helper cache
git config --global credential.helper 'cache --timeout=3600'
# 或者切换到 SSH
git remote set-url origin
[email protected]:user/repo.git
---
## 合并冲突 (Merge Con