版本控制的艺术:从入门到精通的 Git 实战手册
涵盖基础操作、分支策略、高级技巧、团队协作及最佳实践,助你掌握现代软件开发的版本控制核心技能。
Git 是由 Linus Torvalds 于 2005 年创建的分布式版本控制系统(DVCS)。与集中式版本控制系统(如 SVN)不同,Git 在每个开发者的本地机器上维护完整的仓库副本,包括完整的历史记录。这种设计带来了以下核心优势:
Git 管理文件变更通过三个核心区域:
┌─────────────────────────────────────────────────────────┐
│ 工作区 (Working Directory) │
│ 你实际看到的文件,包含所有当前修改 │
├─────────────────────────────────────────────────────────┤
│ 暂存区 (Staging Area / Index) │
│ git add 后,变更进入暂存区,准备提交 │
├─────────────────────────────────────────────────────────┤
│ 仓库 (Repository / HEAD) │
│ git commit 后,变更永久保存到本地仓库 │
└─────────────────────────────────────────────────────────┘
文件状态流转:
Untracked ──git add──► Staged ──git commit──► Committed
▲ │
│ │
└────────git rm --cached───────────────────┘
│
Modified ◄────────git checkout──┘ │
│ │
└────────git reset HEAD────────────────────┘
Git 的核心设计哲学是快照流而非差异比较。每次提交时,Git 会对当前所有文件的状态拍摄一张快照,并保存指向该快照的引用。如果文件没有修改,Git 不会重新存储,而是只保留一个指向上次存储文件的链接。
Commit A Commit B Commit C
┌─────────┐ ┌─────────┐ ┌─────────┐
│ file1 │ │ file1* │ │ file1* │
│ file2 │ │ file2 │ │ file2* │
│ file3 │ │ file3 │ │ file3 │
└─────────┘ └─────────┘ └─────────┘
│ │ │
▼ ▼ ▼
Tree A Tree B Tree C
Git 内部使用四种基本对象类型构建版本历史:
| 对象类型 | 说明 | 类比 |
|---|---|---|
| Blob | 文件内容的二进制表示 | 文件快照 |
| Tree | 目录结构,指向 blob 和其他 tree | 文件夹 |
| Commit | 包含作者、时间、提交信息,指向一个 tree | 版本节点 |
| Tag | 指向特定 commit 的引用 | 书签 |
所有对象通过 SHA-1 哈希值(40位十六进制字符串)唯一标识,存储在 .git/objects 目录中。
# 使用 apt 安装
sudo apt update
sudo apt install git
# 验证安装
git --version
# 使用 Homebrew 安装
brew install git
# 或使用 Xcode Command Line Tools
xcode-select --install
# 下载官方安装包
# https://git-scm.com/download/win
# 或使用 winget
winget install --id Git.Git -e --source winget
安装后必须配置用户信息,这将出现在每次提交中:
# 全局配置(适用于所有仓库)
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# 为特定仓库配置(覆盖全局)
git config user.name "Project Name"
git config user.email "project@company.com"
# 设置默认编辑器(用于编写提交信息)
git config --global core.editor "vim"
# 或 VS Code
git config --global core.editor "code --wait"
# 设置默认分支名
git config --global init.defaultBranch main
# 启用颜色输出
git config --global color.ui auto
# 设置换行符处理(Windows 与 Unix 协作)
git config --global core.autocrlf input # macOS/Linux
git config --global core.autocrlf true # Windows
# 设置别名(大幅提高效率)
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.lg "log --oneline --graph --decorate --all"
# 查看所有配置
git config --list
# 查看特定配置
git config user.name
为了免密码推送代码到远程仓库,配置 SSH 密钥:
# 生成 SSH 密钥对
ssh-keygen -t ed25519 -C "your.email@example.com"
# 启动 SSH Agent
eval "$(ssh-agent -s)"
# 添加私钥
ssh-add ~/.ssh/id_ed25519
# 复制公钥到剪贴板(macOS)
pbcopy < ~/.ssh/id_ed25519.pub
# 或 Linux
xclip -selection clipboard < ~/.ssh/id_ed25519.pub
将公钥添加到 GitHub/GitLab 的 SSH Keys 设置中。
# 方式一:初始化新仓库
git init
# 方式二:克隆远程仓库
git clone https://github.com/user/repo.git
# 克隆指定分支
git clone -b branch-name https://github.com/user/repo.git
# 克隆到指定目录
git clone https://github.com/user/repo.git my-project
# 浅克隆(只下载最近 N 次提交,节省时间和空间)
git clone --depth 1 https://github.com/user/repo.git
# 添加单个文件到暂存区
git add filename.txt
# 添加所有修改
git add .
# 添加特定类型文件
git add *.js
# 交互式添加(选择性添加部分修改)
git add -p
# 查看暂存区的详细变更
git diff --cached
# 基本提交
git commit -m "feat: add user authentication"
# 提交并添加所有已跟踪文件的修改(跳过 git add)
git commit -am "fix: resolve login bug"
# 修改最后一次提交(未推送时)
git commit --amend -m "feat: add user authentication with OAuth"
# 修改最后一次提交但不修改提交信息
git commit --amend --no-edit
# 打开编辑器编写详细提交信息
git commit
提交信息规范(Conventional Commits):
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
常用类型:
feat:新功能fix:修复docs:文档更新style:代码格式(不影响功能)refactor:重构perf:性能优化test:测试相关chore:构建/工具链# 查看工作区状态
git status
# 简洁状态(适合脚本)
git status -s
# 查看文件修改详情
git diff
# 查看已暂存的修改
git diff --cached
# 查看提交历史
git log
# 简洁历史(单行显示)
git log --oneline
# 图形化历史(显示分支合并)
git log --oneline --graph --decorate --all
# 查看特定文件的修改历史
git log -p filename.txt
# 查看每次提交的统计信息
git log --stat
# 查看指定作者提交
git log --author="John"
# 按时间范围查询
git log --since="2024-01-01" --until="2024-12-31"
# 查看指定文件的变更历史
git log --follow -p -- filename.txt
# 撤销工作区修改(未暂存)
git checkout -- filename.txt
# 或新版本
git restore filename.txt
# 撤销暂存(保留修改)
git reset HEAD filename.txt
# 或新版本
git restore --staged filename.txt
# 撤销所有暂存
git reset HEAD .
# 修改最后一次提交
git commit --amend
# 回退到指定版本(保留修改)
git reset --soft HEAD~1
# 回退到指定版本(丢弃修改)
git reset --hard HEAD~1
# 查看所有操作记录(用于找回)
git reflog
# 删除文件(同时从工作区和暂存区移除)
git rm filename.txt
# 仅从暂存区移除(保留工作区文件)
git rm --cached filename.txt
# 重命名文件
git mv old-name.txt new-name.txt
# 相当于:
mv old-name.txt new-name.txt
git rm old-name.txt
git add new-name.txt
分支是 Git 最强大的特性之一。本质上,分支只是一个指向特定提交的轻量级指针。
main
│
▼
A ─── B ─── C ─── D ─── E
│
▼
feature
# 列出所有分支
git branch
# 列出远程分支
git branch -r
# 列出所有分支(本地+远程)
git branch -a
# 创建新分支
git branch feature-login
# 创建并切换到新分支
git checkout -b feature-login
# 或新版本
git switch -c feature-login
# 切换到已有分支
git checkout main
git switch main
# 重命名分支
git branch -m old-name new-name
# 删除已合并分支
git branch -d feature-login
# 强制删除未合并分支
git branch -D feature-login
当目标分支没有新提交时,Git 直接移动指针:
Before: After:
main main
│ │
▼ ▼
A───B───C merge A───B───C───D───E
│ ─────► │
▼ ▼
D───E feature
feature
git checkout main
git merge feature-login
当两个分支都有新提交时,Git 创建合并提交:
Before: After:
main main
│ │
▼ ▼
A───B───C───F A───B───C───F───G
│ │ ─────► │ ╱
│ ▼ │ ╱
└───D───E D───E───
feature feature
git checkout main
git merge feature-login
# 如果有冲突,解决后标记为已解决
git add .
git commit -m "merge: integrate feature-login"
当两个分支修改了同一文件的同一部分,Git 无法自动合并:
# 查看冲突文件
git status
# 查看冲突详情
git diff
# 使用合并工具
git mergetool
# 标记冲突已解决
git add .
# 完成合并
git commit -m "merge: resolve conflicts in auth module"
冲突标记格式:
<<<<<<< HEAD
// 当前分支的代码
const auth = require('./local-auth');
=======
// 合并分支的代码
const auth = require('./oauth');
>>>>>>> feature-login
经典分支模型,适合有发布周期的项目:
main ──*────*────*────*────*────*────*────*───►
╲ ╱ ╲ ╱
develop ─*──*──*──*──*──*──*──*──*──*──*──*──►
╲ ╱ ╲ ╱
feature *──*──* *──*──*
release ───────────────*──*───────────────►
hotfix ────────────────────────*──*────────►
分支说明:
main:生产环境代码develop:开发分支,集成所有功能feature/*:功能开发分支,从 develop 创建release/*:发布准备分支,从 develop 创建hotfix/*:紧急修复分支,从 main 创建简化模型,适合持续部署:
main ──*────*────*────*────*────*────*───►
╲ ╲ ╲
feature *──*──* *──*──* *──*──*
PR+Merge PR+Merge PR+Merge
mainmain 创建分支main结合环境分支:
main ──*────*────*────*────*────*───►
╲ ╲ ╲
feature *──*──* *──*──* *──*──*
PR+Merge PR+Merge PR+Merge
production ─────────────────────*────*──►
main:最新代码production:部署到生产环境pre-production:预发布环境变基将当前分支的提交移到目标分支的最新提交之后,创造更线性的历史:
Before rebase: After rebase:
main main
│ │
▼ ▼
A───B───C───F A───B───C───F
│ │ │
│ ▼ ▼
└───D───E D'──E'
feature feature
# 将 feature 分支变基到 main
git checkout feature
git rebase main
# 交互式变基(修改、合并、删除提交)
git rebase -i HEAD~3
# 常用交互式命令:
# pick - 保留提交
# reword - 修改提交信息
# squash - 合并到上一个提交
# fixup - 合并到上一个提交,丢弃信息
# drop - 删除提交
# edit - 修改提交内容
# 中止变基
git rebase --abort
# 继续变基(解决冲突后)
git rebase --continue
变基 vs 合并的选择:
| 场景 | 推荐操作 | 原因 |
|---|---|---|
| 本地分支整理历史 | rebase |
线性历史更整洁 |
| 公共分支更新代码 | merge |
不改变已发布历史 |
| 功能分支合并到主分支 | merge |
保留完整上下文 |
| 提交前清理本地提交 | rebase -i |
整理提交历史 |
# 查看远程仓库
git remote -v
# 添加远程仓库
git remote add origin https://github.com/user/repo.git
# 修改远程仓库 URL
git remote set-url origin https://new-url.git
# 重命名远程仓库
git remote rename origin upstream
# 删除远程仓库
git remote remove origin
# 查看远程仓库详细信息
git remote show origin
# 推送本地分支到远程
git push origin main
# 推送并建立追踪关系
git push -u origin feature-login
# 强制推送(谨慎使用!)
git push origin main --force
# 安全强制推送(检查远程是否有新提交)
git push origin main --force-with-lease
# 拉取远程更新
git pull origin main
# 拉取但不合并
git fetch origin
# 拉取所有远程分支
git fetch --all
# 拉取并变基(保持线性历史)
git pull --rebase origin main
# 查看本地分支与远程分支的追踪关系
git branch -vv
# 建立追踪关系
git branch --set-upstream-to=origin/main main
# 或简写
git branch -u origin/main
# 推送本地所有分支
git push --all origin
# 删除远程分支
git push origin --delete feature-login
# 或简写
git push origin :feature-login
# 清理本地已删除的远程分支引用
git remote prune origin
# 获取远程更新但不合并
git fetch origin
# 查看远程分支状态
git log --oneline main..origin/main
# 合并远程更新
git merge origin/main
# 变基到远程更新
git rebase origin/main
# 拉取并合并
git pull origin main
# 拉取并变基(推荐)
git pull --rebase origin main
# 添加多个远程仓库
git remote add origin https://github.com/my-fork/repo.git
git remote add upstream https://github.com/original/repo.git
# 获取上游更新
git fetch upstream
# 合并上游更新到本地主分支
git checkout main
git merge upstream/main
# 推送到自己的远程仓库
git push origin main
# 基本日志
git log
# 简洁格式
git log --oneline
# 图形化显示
git log --oneline --graph --decorate --all
# 查看文件历史
git log --follow -p -- filename.txt
# 查看某行代码的修改历史
git blame filename.txt
# 查看指定范围日志
git log --since="2 weeks ago" --until="yesterday"
# 按作者过滤
git log --author="John" --oneline
# 按提交信息搜索
git log --grep="bug fix" --oneline
# 查看文件每次提交的统计
git log --stat -- filename.txt
# 查看某次提交的详情
git show abc1234
# 查看某次提交的文件列表
git show --stat abc1234
# 查看某文件在某版本的内容
git show abc1234:path/to/file.txt
# 查看某文件在两个版本间的差异
git diff abc1234..def5678 -- filename.txt
# 查看工作区与某版本的差异
git diff abc1234 -- filename.txt
# 查看工作区文件到某版本
git checkout abc1234 -- filename.txt
# 恢复整个工作区到某版本(不移动 HEAD)
git checkout abc1234 -- .
# 创建新分支指向历史版本
git checkout -b old-version abc1234
# 回退到某版本(保留修改)
git reset --soft abc1234
# 回退到某版本(丢弃修改)
git reset --hard abc1234
# 回退到某版本(保留修改但不暂存)
git reset --mixed abc1234
# 在提交历史中搜索代码
git log -S "function_name" --oneline
# 在提交历史中搜索代码(使用正则)
git log -G "regex_pattern" --oneline
# 搜索提交信息
git log --all --grep="keyword"
# 搜索特定作者的提交
git log --all --author="name" --oneline
# 查看某行代码何时被修改
git blame -L 10,20 filename.txt
交互式变基是整理提交历史的最强大工具:
# 整理最近 5 次提交
git rebase -i HEAD~5
# 整理从某提交开始的所有提交
git rebase -i abc1234
交互式变基命令:
pick abc1234 feat: add login form
reword def5678 fix: validate email
squash ghi9012 fix: password validation
fixup jkl3456 style: format code
edit mno7890 refactor: extract auth service
drop pqr1234 test: add failing test
将特定提交应用到当前分支:
# 拣选单个提交
git cherry-pick abc1234
# 拣选多个提交
git cherry-pick abc1234 def5678
# 拣选提交范围
git cherry-pick abc1234^..def5678
# 拣选但不自动提交
git cherry-pick -n abc1234
# 拣选时保留原提交信息
git cherry-pick -x abc1234
# 软重置:回退到某版本,保留修改且已暂存
git reset --soft HEAD~1
# 混合重置(默认):回退到某版本,保留修改但未暂存
git reset --mixed HEAD~1
# 硬重置:回退到某版本,丢弃所有修改
git reset --hard HEAD~1
# 重置特定文件到某版本
git checkout abc1234 -- filename.txt
# 重置到远程分支状态
git reset --hard origin/main
创建新提交来撤销某次提交的变更:
# 还原某次提交(创建新的撤销提交)
git revert abc1234
# 还原多次提交
git revert abc1234 def5678
# 还原但不自动提交
git revert -n abc1234
# 还原合并提交
git revert -m 1 abc1234
reset vs revert:
| 命令 | 效果 | 适用场景 |
|---|---|---|
reset |
修改历史,删除提交 | 本地分支整理 |
revert |
创建新提交,保留历史 | 公共分支撤销 |
临时保存未提交的修改:
# 储藏当前修改
git stash
# 储藏并添加描述
git stash push -m "WIP: login feature"
# 查看储藏列表
git stash list
# 应用最近储藏(不删除)
git stash apply
# 应用指定储藏
git stash apply stash@{2}
# 应用并删除最近储藏
git stash pop
# 删除最近储藏
git stash drop
# 删除指定储藏
git stash drop stash@{1}
# 清空所有储藏
git stash clear
# 查看储藏内容
git stash show -p stash@{0}
# 储藏未跟踪文件
git stash push -u -m "include new files"
# 储藏所有文件(包括忽略文件)
git stash push -a -m "everything"
# 查看将被清理的文件
git clean -n
# 删除未跟踪文件
git clean -f
# 删除未跟踪文件和目录
git clean -fd
# 删除忽略文件
git clean -fx
# 删除未跟踪文件和忽略文件
git clean -fdx
# 交互式清理
git clean -i
# 创建轻量标签
git tag v1.0.0
# 创建附注标签(推荐)
git tag -a v1.0.0 -m "Release version 1.0.0"
# 为特定提交创建标签
git tag -a v1.0.0 abc1234 -m "Version 1.0.0"
# 创建签名标签(需要 GPG)
git tag -s v1.0.0 -m "Signed release"
# 列出所有标签
git tag
# 列出匹配模式的标签
git tag -l "v1.*"
# 查看标签详情
git show v1.0.0
# 删除本地标签
git tag -d v1.0.0
# 推送标签到远程
git push origin v1.0.0
# 推送所有标签
git push origin --tags
# 删除远程标签
git push origin --delete v1.0.0
标签命名遵循语义化版本规范:
版本格式:主版本号.次版本号.修订号(MAJOR.MINOR.PATCH)
1.0.0 # 初始稳定版本
1.1.0 # 新增功能(向后兼容)
1.1.1 # 修复问题(向后兼容)
2.0.0 # 重大更新(不兼容变更)
在父仓库中嵌入其他仓库:
# 添加子模块
git submodule add https://github.com/user/lib.git libs/lib
# 克隆包含子模块的仓库
git clone --recurse-submodules https://github.com/user/project.git
# 初始化子模块(已克隆后)
git submodule update --init
# 更新子模块
git submodule update --remote
# 递归更新所有子模块
git submodule update --init --recursive
# 删除子模块
# 1. 删除 .gitmodules 中相关部分
# 2. 删除 .git/config 中相关部分
# 3. 运行 git rm --cached path/to/submodule
# 4. 删除子模块目录
将其他仓库合并到子目录:
# 添加子树
git subtree add --prefix=libs/lib https://github.com/user/lib.git main --squash
# 更新子树
git subtree pull --prefix=libs/lib https://github.com/user/lib.git main --squash
# 推送子树修改到上游
git subtree push --prefix=libs/lib https://github.com/user/lib.git main
子模块 vs 子树:
| 特性 | 子模块 | 子树 |
|---|---|---|
| 复杂度 | 较高 | 较低 |
| 依赖管理 | 独立仓库 | 合并到主仓库 |
| 克隆 | 需要额外步骤 | 一次克隆完成 |
| 修改子项目 | 需要进入子模块目录 | 直接在子目录修改 |
| 适用场景 | 独立维护的库 | 紧密耦合的代码 |
Git 钩子是在特定事件发生时自动执行的脚本:
客户端钩子:
pre-commit:提交前执行(代码检查)prepare-commit-msg:打开编辑器前执行(修改默认提交信息)commit-msg:提交信息编辑后执行(验证提交格式)post-commit:提交完成后执行(通知)pre-rebase:变基前执行post-checkout:检出后执行post-merge:合并后执行pre-push:推送前执行(运行测试)服务端钩子:
pre-receive:接收推送前执行(验证推送)update:更新分支时执行post-receive:接收推送后执行(部署)pre-commit:代码格式化检查
#!/bin/sh
# .git/hooks/pre-commit
# 运行代码检查
npm run lint
if [ $? -ne 0 ]; then
echo "代码检查失败,请修复后重新提交"
exit 1
fi
# 运行测试
npm test
if [ $? -ne 0 ]; then
echo "测试失败,请修复后重新提交"
exit 1
fi
commit-msg:提交信息格式验证
#!/bin/sh
# .git/hooks/commit-msg
commit_msg=$(cat $1)
pattern="^(feat|fix|docs|style|refactor|perf|test|chore)(\(.+\))?: .{1,100}$"
if ! echo "$commit_msg" | grep -qE "$pattern"; then
echo "提交信息格式错误!请使用 Conventional Commits 格式:"
echo "type(scope): description"
exit 1
fi
pre-push:推送前运行测试
#!/bin/sh
# .git/hooks/pre-push
# 获取当前分支
branch=$(git rev-parse --abbrev-ref HEAD)
# 主分支推送前运行完整测试
if [ "$branch" = "main" ]; then
echo "正在运行集成测试..."
npm run test:integration
if [ $? -ne 0 ]; then
echo "集成测试失败,推送中止"
exit 1
fi
fi
.git/
├── HEAD # 指向当前分支
├── config # 仓库配置
├── description # 仓库描述
├── hooks/ # 钩子脚本
├── index # 暂存区
├── info/ # 排除模式等
├── objects/ # Git 对象数据库
│ ├── info/
│ └── pack/ # 压缩的对象包
├── refs/ # 引用存储
│ ├── heads/ # 分支指针
│ ├── tags/ # 标签指针
│ └── remotes/ # 远程分支指针
└── logs/ # 引用日志
Git 使用内容寻址文件系统存储数据:
# 查看对象类型
git cat-file -t abc1234
# 查看对象内容
git cat-file -p abc1234
# 查看 tree 对象
git ls-tree abc1234
# 查看 blob 对象
git show abc1234:filename.txt
# 查看提交对象
git show --format=raw abc1234
# 查看 HEAD 指向
cat .git/HEAD
# 查看分支指向
cat .git/refs/heads/main
# 查看所有引用
git show-ref
# 查看引用日志
git reflog
# 查看引用日志详情
git reflog show main
Git 定期将松散对象打包以节省空间:
# 手动触发垃圾回收
git gc
# 查看包文件信息
git count-objects -vH
# 验证对象数据库完整性
git fsck
# 查看包文件内容
git verify-pack -v .git/objects/pack/pack-*.idx
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
示例:
feat(auth): add OAuth2 login support
Implement Google and GitHub OAuth2 login flow.
Add user profile synchronization.
Closes #123
Fixes #123 或 Closes #456# 功能分支
feature/user-authentication
feature/payment-integration
# 修复分支
fix/login-error-123
fix/memory-leak
# 热修复分支
hotfix/security-patch-2024
hotfix/critical-bug
# 发布分支
release/v2.1.0
release/2024-q1
# 文档分支
docs/api-reference
docs/setup-guide
# 重构分支
refactor/database-layer
refactor/dependency-injection
提交 Pull Request 前自查:
1. 更新主分支
git checkout main
git pull origin main
2. 创建功能分支
git checkout -b feature/new-feature
3. 开发并提交
git add .
git commit -m "feat: implement new feature"
4. 保持分支同步
git fetch origin
git rebase origin/main
5. 推送分支
git push -u origin feature/new-feature
6. 创建 Pull Request
7. 代码审查通过
8. 合并到主分支
git checkout main
git merge feature/new-feature
git push origin main
9. 删除功能分支
git branch -d feature/new-feature
git push origin --delete feature/new-feature
# 使用稀疏检出管理大型仓库
git clone --filter=blob:none --no-checkout https://github.com/large/repo.git
cd repo
git sparse-checkout init --cone
git sparse-checkout set projects/web projects/api
git checkout main
# 无 blob 克隆(按需下载文件内容)
git clone --filter=blob:none https://github.com/large/repo.git
# 无 tree 克隆(更激进)
git clone --filter=tree:0 https://github.com/large/repo.git
# 浅克隆(只下载最近历史)
git clone --depth 1 https://github.com/large/repo.git
# 查看冲突文件
git status
# 查看冲突详情
git diff
# 使用合并工具
git mergetool
# 标记已解决
git add .
# 完成合并
git commit -m "merge: resolve conflicts"
# 放弃合并
git merge --abort
# 误删文件(未提交)
git checkout -- filename.txt
# 误删提交(查看 reflog)
git reflog
# 找到删除前的 commit hash
git checkout -b recovery-branch abc1234
# 误删分支
git reflog
# 找到分支最后的 commit
git checkout -b deleted-branch-name abc1234
# 强制推送后恢复
git reflog
# 找到强制推送前的状态
git reset --hard abc1234
# 查找大文件
git rev-list --objects --all | \
git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | \
awk '/^blob/ {print $3 " " $4}' | sort -rn | head -20
# 使用 Git LFS 管理大文件
git lfs install
git lfs track "*.psd"
git lfs track "*.zip"
git add .gitattributes
# 从历史中删除大文件(谨慎使用!)
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch path/to/large-file' \
--prune-empty --tag-name-filter cat -- --all
# 垃圾回收
git gc
# 激进垃圾回收
git gc --aggressive
# 查看仓库大小
git count-objects -vH
# 查找冗余对象
git fsck --full
# 压缩松散对象
git repack -ad
# 清理 reflog(缩短保留期)
git reflog expire --expire=30.days --all
# 缓存凭证(15分钟)
git config --global credential.helper cache
# 长期缓存凭证
git config --global credential.helper store
# macOS Keychain
git config --global credential.helper osxkeychain
# Windows Credential Manager
git config --global credential.helper manager
# 删除缓存的凭证
git credential-cache exit
| 命令 | 说明 |
|---|---|
git init |
初始化仓库 |
git clone <url> |
克隆仓库 |
git status |
查看状态 |
git add <file> |
添加文件到暂存区 |
git add . |
添加所有修改 |
git commit -m "msg" |
提交变更 |
git commit -am "msg" |
添加并提交 |
git push |
推送到远程 |
git pull |
拉取并合并 |
git fetch |
获取远程更新 |
| 命令 | 说明 |
|---|---|
git branch |
列出分支 |
git branch <name> |
创建分支 |
git checkout <branch> |
切换分支 |
git checkout -b <name> |
创建并切换 |
git switch <branch> |
切换分支(新) |
git switch -c <name> |
创建并切换(新) |
git merge <branch> |
合并分支 |
git rebase <branch> |
变基分支 |
git branch -d <name> |
删除分支 |
git branch -D <name> |
强制删除 |
| 命令 | 说明 |
|---|---|
git log |
查看历史 |
git log --oneline |
简洁历史 |
git log --graph |
图形化历史 |
git diff |
查看未暂存差异 |
git diff --cached |
查看已暂存差异 |
git show <commit> |
查看提交详情 |
git blame <file> |
逐行查看作者 |
git reflog |
查看操作记录 |
| 命令 | 说明 |
|---|---|
git restore <file> |
恢复文件 |
git restore --staged <file> |
取消暂存 |
git reset --soft HEAD~1 |
软重置 |
git reset --hard HEAD~1 |
硬重置 |
git revert <commit> |
还原提交 |
git commit --amend |
修改最后提交 |
git stash |
储藏修改 |
git stash pop |
应用并删除储藏 |
| 命令 | 说明 |
|---|---|
git remote -v |
查看远程仓库 |
git remote add <name> <url> |
添加远程 |
git push <remote> <branch> |
推送分支 |
git pull <remote> <branch> |
拉取分支 |
git fetch <remote> |
获取更新 |
git push --set-upstream <remote> <branch> |
推送并追踪 |
| 命令 | 说明 |
|---|---|
git tag |
列出标签 |
git tag <name> |
创建轻量标签 |
git tag -a <name> -m "msg" |
创建附注标签 |
git push origin <tag> |
推送标签 |
git push origin --tags |
推送所有标签 |
git tag -d <name> |
删除标签 |
# 用户信息
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# 编辑器
git config --global core.editor "code --wait"
# 默认分支
git config --global init.defaultBranch main
# 颜色输出
git config --global color.ui auto
# 推送策略
git config --global push.default simple
# 拉取策略
git config --global pull.rebase true
# 合并策略
git config --global merge.ff false
# 别名
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
文档信息
- 版本:v2.0
- 更新日期:2026-04-27
- 适用 Git 版本:2.30+
- 维护建议:Git 持续更新,建议定期查阅官方文档获取最新特性
本文档涵盖 Git 从基础到高级的完整知识体系,建议根据实际工作场景选择性深入。记住:Git 的强大在于它的灵活性,但团队协作需要一致性——遵循规范,善用工具,让版本控制成为效率的助推器而非阻碍。