Skip to main content
Version: 3.0.1

Git 常见问题与解决方案

本章将介绍 Git 使用过程中常见的问题及其解决方案,帮助你快速排除故障。

常见错误与修复

1. 提交到错误的分支

问题: 在错误的分支上进行了提交

解决方案:

# 1. 切换到正确的分支
git checkout correct-branch

# 2. 将提交从错误分支复制到正确分支
git cherry-pick commit-hash

# 3. 删除错误分支上的提交
git checkout wrong-branch
git reset --hard HEAD~1

2. 提交信息错误

问题: 提交信息写错了

解决方案:

# 修改最后一次提交信息
git commit --amend -m "正确的提交信息"

# 强制推送到远程(如果已经推送)
git push --force-with-lease origin branch-name

3. 忘记添加文件到提交

问题: 提交后发现漏了文件

解决方案:

# 添加遗漏的文件
git add forgotten-file.txt

# 修改最后一次提交
git commit --amend --no-edit

合并冲突解决

识别冲突

当合并出现冲突时,Git 会标记冲突文件:

<<<<<<< HEAD
你的修改
=======
别人的修改
>>>>>>> branch-name

解决冲突步骤

  1. 打开冲突文件
  2. 手动解决冲突(保留需要的代码,删除标记)
  3. 添加解决后的文件
  4. 完成合并
# 手动编辑文件解决冲突后
git add resolved-file.txt
git commit -m "解决合并冲突"

撤销操作

撤销未提交的修改

# 撤销单个文件的修改
git checkout -- filename.txt

# 撤销所有修改
git checkout -- .

# 撤销所有修改(包括新文件)
git clean -fd
git checkout -- .

撤销已提交的修改

# 撤销最后一次提交(保留修改)
git reset --soft HEAD~1

# 撤销最后一次提交(丢弃修改)
git reset --hard HEAD~1

# 撤销特定提交
git revert commit-hash

远程仓库问题

推送被拒绝

问题: ! [rejected] main -> main (non-fast-forward)

解决方案:

# 先拉取远程更新
git pull origin main

# 解决可能的冲突
# 然后重新推送
git push origin main

删除远程分支

# 删除远程分支
git push origin --delete branch-name

# 或者使用更短的语法
git push origin :branch-name

文件权限问题

文件权限变化导致差异

# 忽略文件权限变化
git config core.filemode false

# 或者只针对当前仓库
git config --local core.filemode false

仓库维护

清理仓库

# 删除未跟踪的文件
git clean -n # 预览
git clean -f # 执行删除

# 优化仓库
git gc --aggressive

# 重新打包对象
git repack -a -d --depth=250 --window=250

修复损坏的仓库

# 检查仓库完整性
git fsck

# 恢复丢失的对象
git reflog
git checkout recovered-commit

配置问题

查看和修改配置

# 查看所有配置
git config --list

# 查看特定配置
git config user.name

# 修改配置
git config --global user.name "New Name"

代理设置

# 设置 HTTP 代理
git config --global http.proxy http://proxy.example.com:8080

# 设置 HTTPS 代理
git config --global https.proxy https://proxy.example.com:8080

# 取消代理设置
git config --global --unset http.proxy
git config --global --unset https.proxy

性能优化

加速操作

# 启用文件系统缓存
git config --global core.preloadindex true
git config --global core.fscache true
git config --global gc.auto 256

# 使用更快的压缩算法
git config --global core.compression 0

大文件处理

# 使用 Git LFS 处理大文件
git lfs install
git lfs track "*.psd"
git add .gitattributes

实用技巧

查找引入 bug 的提交

# 使用二分查找
git bisect start
git bisect bad
git bisect good commit-hash
# 测试当前版本,然后标记 good 或 bad
git bisect reset

查看文件历史

# 查看文件的修改历史
git log -p filename.txt

# 查看谁修改了某行代码
git blame filename.txt

搜索提交内容

# 搜索包含特定文本的提交
git log --grep="搜索文本"

# 搜索代码中的文本
git grep "搜索文本"

这些解决方案涵盖了 Git 使用中的常见问题,掌握它们可以帮助你更高效地使用 Git。