# Git 命令速查表（完整版） · Git Cheat Sheet (Full)

> 完整版：收录 14 个分类共 116 条命令，含进阶参数、暂存现场管理、排查与维护。三栏对照：命令 / 中文解释 / 英文解释。

## GIT BASICS · 基础

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git init <directory>` | 在指定目录创建一个空的 Git 仓库；不带参数则在当前目录创建 | Create an empty Git repo in the specified directory. Run with no arguments to initialize the current directory. |
| `git init -b main <directory>` | 初始化仓库并把初始分支命名为 main（也可全局设置 init.defaultBranch） | Initialize a repo and name the initial branch main (or set init.defaultBranch globally). |
| `git clone <repo>` | 克隆仓库到本地；<repo> 可以是本地路径，也可以是 HTTP / SSH 远程地址 | Clone the repo onto your machine. The repo can be on the local filesystem or on a remote machine via HTTP or SSH. |
| `git clone --depth 1 <repo>` | 浅克隆：只取最近一次提交，适合大仓库与 CI | Shallow clone: fetch only the latest commit. Useful for large repos and CI. |
| `git clone --recurse-submodules <repo>` | 克隆时一并检出子模块 | Clone the repo and check out its submodules as well. |
| `git config user.name "<name>"` | 为当前仓库设置提交者姓名（加 --global 则为全局） | Set the author name for commits in the current repo (add --global for your user). |
| `git config user.email "<email>"` | 为当前仓库设置提交者邮箱（加 --global 则为全局） | Set the author email for commits in the current repo (add --global for your user). |
| `git add -A` | 暂存全部改动，包括新增与删除 | Stage all changes, including additions and deletions. |
| `git add -p` | 交互式挑选代码块暂存，一次提交只包含一部分改动 | Interactively pick hunks to stage, so one commit contains only part of your changes. |
| `git commit -m "<message>"` | 提交暂存区内容，直接用 <message> 作为提交信息，不打开编辑器 | Commit the staged snapshot with <message> as the commit message instead of opening an editor. |
| `git commit -v` | 提交时在编辑器里附带 diff，便于写清提交信息 | Commit with the diff shown in the editor, handy for writing a precise message. |
| `git status` | 查看哪些改动已暂存、未暂存，以及未跟踪的文件 | List which files are staged, unstaged and untracked. |
| `git status -sb` | 短格式状态，并显示当前分支与领先 / 落后远程的情况 | Short status plus the current branch and how far it is ahead of or behind the remote. |

## GIT DIFF · 比较

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git diff` | 工作区与暂存区的差异 | Show unstaged changes between your index and the working directory. |
| `git diff --staged` | 暂存区与上次提交的差异（与 --cached 等价） | Show staged changes against the last commit (same as --cached). |
| `git diff HEAD` | 工作区与上次提交的差异 | Show the difference between the working directory and the last commit. |
| `git diff --stat` | 只列出改动的文件与增删行数概览 | Show a per-file summary of added and removed lines. |
| `git diff main...feature` | 从两个分支的共同祖先开始比较，评审分支时常用 | Compare starting from the merge base of the two branches. |
| `git diff --word-diff` | 词级差异，更适合文档与长行代码 | Word-level diff, easier to read for prose and long lines. |

## UNDOING CHANGES · 撤销修改

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git revert <commit>` | 生成一个反向提交来抵消指定提交，不改写历史 | Create a new commit that undoes all the changes made in <commit>, then apply it to the current branch. |
| `git revert -n <c1> <c2>` | 连续撤销多个提交而不逐个生成提交，最后统一提交一次 | Revert several commits without committing each; commit once at the end. |
| `git restore --staged <file>` | 把文件移出暂存区，工作区内容保持不变 | Remove <file> from the staging area but leave the working directory unchanged. |
| `git restore <file>` | 丢弃工作区对该文件的修改（不可恢复） | Discard working-directory changes to <file>; this cannot be undone. |
| `git restore --source=<commit> -- <file>` | 把文件恢复成某次提交里的内容 | Restore <file> to the version it had in <commit>. |
| `git stash -u` | 把未提交的改动（含未跟踪文件）先收起来，稍后可恢复 | Stash uncommitted changes, including untracked files, to restore them later. |

## REWRITING GIT HISTORY · 改写历史

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git commit --amend --no-edit` | 把当前暂存改动并入上一次提交，保留原提交信息 | Replace the last commit with the staged changes and last commit combined, keeping its message. |
| `git commit --amend --reset-author` | 并入改动并把提交者改成自己 | Amend the last commit and make yourself the author. |
| `git commit --fixup=<commit>` | 生成 fixup! 提交，稍后用 rebase --autosquash 自动整理 | Create a fixup commit to be squashed later by rebase --autosquash. |
| `git commit --fixup=amend:<commit>` | 生成同时修正提交信息的 fixup 提交 | Same as a fixup commit, but the target's message is amended too. |
| `git rebase <base>` | 把当前分支变基到 <base>；<base> 可以是提交、分支名、标签或 HEAD~n | Rebase the current branch onto <base>: a commit ID, branch name, tag or relative reference to HEAD. |
| `git rebase --rebase-merges <base>` | 保留合并结构的变基（取代已废弃的 --preserve-merges） | Rebase while preserving merge topology (replaces the deprecated --preserve-merges). |
| `git rebase --autostash` | 变基前后自动 stash / 恢复未提交的改动 | Automatically stash and re-apply uncommitted changes around the rebase. |
| `git reflog` | 查看 HEAD 的移动历史，误操作后的找回入口 | Show a log of changes to the local repository's HEAD, your way back after mistakes. |

## GIT BRANCHES · 分支

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git branch` | 列出本地分支 | List all of the branches in your repo. |
| `git branch -vv` | 列出分支及其上游跟踪关系、领先 / 落后情况 | List branches with their upstream and ahead / behind status. |
| `git branch --show-current` | 只打印当前分支名 | Print just the name of the current branch. |
| `git branch -m <new-name>` | 重命名当前分支（-M 强制覆盖同名分支） | Rename the current branch (use -M to force the overwrite). |
| `git switch -c <branch>` | 创建并切换到新分支；去掉 -c 即切换到已有分支 | Create and switch to a new branch named <branch>. Drop the -c flag to switch to an existing branch. |
| `git switch <branch>` | 切换到已有分支 | Switch to an existing branch. |
| `git switch -` | 回到上一个分支 | Switch back to the previous branch. |
| `git switch --track origin/<branch>` | 基于远程分支创建本地跟踪分支 | Create a local branch that tracks the given remote branch. |
| `git merge <branch>` | 把指定分支合并进当前分支 | Merge <branch> into the current branch. |
| `git merge --no-ff <branch>` | 禁止快进，始终留下一个合并提交 | Merge with a merge commit even when a fast-forward is possible. |
| `git merge --ff-only <branch>` | 只允许快进，否则报错退出 | Merge only when it can be a fast-forward, otherwise stop. |
| `git merge --squash <branch>` | 把对方分支的改动压成一批未提交的改动 | Squash all changes from the branch into a single set of uncommitted changes. |

## REMOTE REPOSITORIES · 远程仓库

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git remote add <name> <url>` | 添加一个远程仓库，之后可用 <name> 代替 <url> | Create a new connection to a remote repo; afterwards use <name> as a shortcut for <url>. |
| `git remote -v` | 列出所有远程仓库及其地址 | List all remotes together with their URLs. |
| `git remote set-url <name> <url>` | 修改远程仓库地址，例如 HTTPS 与 SSH 互切 | Change a remote's URL, for example to switch between HTTPS and SSH. |
| `git remote prune origin` | 清理远程已删除分支留下的本地引用 | Remove local references to branches that no longer exist on the remote. |
| `git fetch <remote> <branch>` | 抓取指定远程分支的提交；省略 <branch> 则抓取全部远程引用 | Fetch a specific branch from the remote. Leave off <branch> to fetch all remote refs. |
| `git fetch --all --prune` | 抓取所有远程，并清理远程已删除的分支 | Fetch from all remotes and prune branches deleted upstream. |
| `git fetch --prune-tags` | 同时清理远程已删除的标签 | Also remove tags that no longer exist on the remote. |
| `git pull --rebase <remote>` | 抓取后以 rebase 方式并入，历史保持线性 | Fetch the remote's copy of the current branch and rebase your local commits on top of it. |
| `git pull --ff-only <remote>` | 只允许快进式拉取，否则退出，不做任何合并 | Fast-forward only: stop instead of creating an unexpected merge commit. |
| `git push -u origin <branch>` | 推送分支并建立 upstream 跟踪关系 | Push the branch and set its upstream in one step. |

## GIT CONFIG · 配置

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git config --global user.name "<name>"` | 配置当前用户的提交者姓名 | Define the author name used for all commits by the current user. |
| `git config --global user.email "<email>"` | 配置当前用户的提交者邮箱 | Define the author email used for all commits by the current user. |
| `git config --global init.defaultBranch main` | 新仓库的默认初始分支名 | Set the default initial branch name for newly created repositories. |
| `git config --global pull.rebase true` | pull 默认使用 rebase；不想 rebase 可改设 pull.ff only | Make pull rebase by default; set pull.ff only instead to forbid merges. |
| `git config --global push.autoSetupRemote true` | 新分支直接 git push 也能自动建立跟踪 | Let a plain git push set up tracking for a new branch. |
| `git config --global fetch.prune true` | fetch 时自动清理远程已删除的分支 | Prune deleted remote branches on every fetch. |
| `git config --global rerere.enabled true` | 记住冲突的解决方式，下次遇到同样冲突自动套用 | Reuse recorded resolution: replay how you resolved the same conflict before. |
| `git config --global merge.conflictStyle zdiff3` | 冲突标记更易读：显示共同祖先，并裁掉两侧重复行 | Use the zdiff3 conflict style: show the common ancestor and trim the lines both sides share. |
| `git config --global core.editor "<editor>"` | 设置默认文本编辑器，例如 vim、nvim、code --wait | Set the text editor Git launches when one is needed, e.g. vim, nvim or "code --wait". |
| `git config --global alias.<alias-name> "<git-command>"` | 配置命令别名，例如 alias.lg "log --oneline --graph --decorate --all" | Create a shortcut for a Git command, e.g. alias.lg "log --oneline --graph --decorate --all". |
| `git config --global --edit` | 打开全局配置文件手动编辑 | Open the global configuration file in a text editor for manual editing. |
| `git config --list --show-origin` | 列出所有生效的配置及其来源文件 | List every effective setting together with the file it comes from. |
| `git config --global includeIf "gitdir:~/work/"` | 为特定目录下的仓库套用另一套配置，例如工作身份 | Apply a different configuration, such as a work identity, to repos under a given path. |

## GIT LOG · 日志

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git log -<limit>` | 限制显示条数，例如 git log -5 只看最近 5 条提交 | Limit the number of commits shown, e.g. git log -5 limits it to five. |
| `git log --oneline` | 每条提交压成一行显示 | Condense each commit to a single line. |
| `git log --oneline --graph --decorate --all` | 一行一条，附分支拓扑图、引用标签与全部分支 | One line per commit with a graph, ref decorations and all branches. |
| `git log --author="<pattern>"` | 按作者筛选提交 | Search for commits by a particular author. |
| `git log --grep="<pattern>"` | 按提交信息内容筛选提交 | Search for commits whose commit message matches <pattern>. |
| `git log -S "<string>"` | 查找引入或删除某段字符串的提交（pickaxe） | Find the commits that added or removed a given string (the pickaxe). |
| `git log <since>..<until>` | 查看两个引用之间的提交 | Show commits between <since> and <until>: commit IDs, branches, HEAD or relative refs. |
| `git log --first-parent` | 只看主干线上的提交，忽略分支内部细节 | Follow only the first parent, the mainline view. |
| `git log --show-pulls` | 在文件历史里一并显示把改动带进来的合并提交 | Also show the merge commits that brought changes in, in path-limited history. |
| `git log --follow -- <file>` | 跟踪单个文件的完整历史，包括改名之前的部分 | Follow a single file's history, including the part before it was renamed. |
| `git log -p -- <file>` | 逐条显示该文件收到的改动补丁 | Show the patches a file received, commit by commit. |
| `git log --graph` | 用文本图形展示提交与分支结构 | Draw a text-based graph of commits on the left side of the messages. |

## GIT RESET · 回退

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git reset` | 清空暂存区，工作区保持不变（等价于 git restore --staged .） | Reset the staging area to match the most recent commit, but leave the working directory unchanged. |
| `git reset --soft <commit>` | 回退到指定提交，改动全部留在暂存区 | Move the branch back to <commit> and keep every change staged. |
| `git reset <commit>` | 回退到指定提交，改动退回工作区（默认即 --mixed） | Move the branch tip back to <commit>, reset the index and leave the working directory alone. |
| `git reset --keep <commit>` | 回退但保留未提交的本地修改，若有冲突则中止 | Reset while keeping uncommitted local changes that do not conflict. |
| `git reset --hard <commit>` | 回退到指定提交，并丢弃其后的所有提交与全部未提交改动 | Move the branch tip back and overwrite the staging area and working directory; uncommitted work is lost. |

## GIT REBASE · 变基

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git rebase -i <base>` | 交互式变基：合并、重排、改写信息、删除或编辑提交 | Interactively rebase onto <base>: squash, reorder, reword, drop or edit each commit. |
| `git rebase -i --autosquash <base>` | 自动把 fixup! / squash! 提交排到目标提交之后 | Automatically place fixup! and squash! commits next to their target commit. |
| `git rebase -i --update-refs <base>` | 变基时同步更新指向区间内提交的其他分支 | Update other branches that point at commits inside the rebased range. |
| `git rebase --onto <newbase> <oldbase>` | 把一段提交整体搬到新的基底上 | Transplant a range of commits onto a new base. |
| `git rebase --continue` / `--abort` / `--skip` | 冲突处理：继续变基 / 放弃变基 / 跳过当前提交 | Conflict handling: continue the rebase, abort it, or skip the current commit. |

## GIT PULL · 拉取

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git pull <remote>` | 抓取当前分支并立即合并；现代做法是显式写明 --rebase 或 --ff-only | Fetch the remote's copy of the current branch and merge it; prefer an explicit --rebase or --ff-only today. |
| `git pull --rebase <remote>` | 抓取后以 rebase 方式并入本地分支，而不是 merge | Fetch and rebase the remote branch into your local copy instead of merging. |
| `git pull --ff-only <remote>` | 只允许快进，否则报错退出 | Fail instead of creating a merge when a fast-forward is not possible. |

## GIT PUSH · 推送

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git push <remote> <branch>` | 把本地分支推送到远程；远程没有对应分支时会自动创建 | Push the branch to <remote> along with the necessary commits; the branch is created if it does not exist. |
| `git push -u <remote> <branch>` | 首次推送并建立 upstream 跟踪关系 | Push a branch for the first time and set its upstream. |
| `git push --force-with-lease` | 非快进推送，但仅当远程仍是你已知的版本时才允许覆盖 | Force the push only if the remote ref is still the one you have seen; safer than --force. |
| `git push --force-with-lease --force-if-includes` | 再加一层保护：确保你确实看过远程最新的提交 | Add an extra check that the remote tip was actually examined before overwriting it. |
| `git push --force` | 无条件覆盖远程分支，会丢掉别人的提交，仅在个人分支上用 | Overwrite the remote branch unconditionally; it can drop other people's commits, so use it only on your own branches. |
| `git push --follow-tags` | 推送提交，并附带推送与之相关的注释标签（比 --tags 更常用） | Push the commits plus the annotated tags that point at them (the everyday alternative to --tags). |
| `git push --tags` | 推送全部本地标签，适合迁移仓库或批量补标签 | Send all of your local tags to the remote repo; useful when migrating or backfilling tags. |
| `git push origin --delete <branch>` | 删除远程分支 | Delete a branch on the remote. |
| `git push --dry-run` | 试推一次，只报告会做什么，不真正推送 | Do everything except actually send, so you can see what would happen. |

## STASH, WORKTREE & CLEAN · 暂存现场与工作区

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git stash push -m "<message>"` | 把当前修改收进 stash 并附上说明 | Stash the current changes and label them with a message. |
| `git stash list` | 列出所有 stash | List all of the stashes you have saved. |
| `git stash pop` | 恢复最近一次 stash，并从列表中移除 | Apply the most recent stash and drop it from the list. |
| `git stash apply <stash>` | 恢复指定 stash，但保留这条记录 | Apply a stash but keep it in the list. |
| `git worktree add <path> <branch>` | 在另一个目录同时检出别的分支，互不干扰 | Check out another branch in a separate directory at the same time. |
| `git worktree list` | 列出所有工作区 | List all worktrees of the repository. |
| `git clean -nd` | 干跑：先看看哪些未跟踪文件会被删掉 | Dry run: show which untracked files would be removed. |
| `git clean -fd` | 真正删除未跟踪文件与目录（不可恢复） | Actually remove untracked files and directories; this cannot be undone. |

## INSPECTION & MAINTENANCE · 排查与维护

| 命令 | 中文解释 | 英文解释 |
|---|---|---|
| `git range-diff <range1> <range2>` | 比较两轮补丁序列的差异，rebase 前后到底改了什么 | Compare two versions of a patch series, e.g. before and after a rebase. |
| `git bisect run <script>` | 用脚本自动二分，定位引入问题的那个提交 | Automatically binary-search the commit that introduced a problem, using a script. |
| `git blame --ignore-rev <rev>` | 忽略某次提交（例如批量格式化）来定位真正的改动者 | Blame while ignoring a commit, such as a mass reformat. |
| `git blame --ignore-revs-file <file>` | 忽略文件里列出的所有提交 | Ignore every commit listed in the given file. |
| `git maintenance start` | 让 Git 自己调度后台维护任务，如 gc 与预取 | Let Git schedule background maintenance such as gc and prefetch. |
| `git sparse-checkout set <dir>` | 大仓库只检出需要的目录 | Check out only the directories you need in a large repository. |
