# 关于 Git 变基

git rebase 命令使您能够轻松更改一系列提交，修改仓库历史。 您可以重新排序、编辑提交或将提交压缩到一起。

通常，你会使用 `git rebase` 来：

* 编辑之前的提交消息
* 将多个提交合并为一个
* 删除或还原不需要的提交

> \[!WARNING]
> 由于更改提交历史记录可能会给其他使用该存储库的人带来困难，因此通常认为如果提交已经推送到存储库，执行提交变基是不好的做法。 若要了解如何安全地变基，请参阅 [合并拉取请求](/zh/enterprise-server@3.22/pull-requests/collaborating-with-pull-requests/incorporating-changes-from-a-pull-request/about-pull-request-merges)。

## 对分支变基提交

若要重新设置另一个分支和当前分支状态之间的所有提交，可以在 shell 中输入以下命令（Windows的命令提示符或 Mac 和 Linux 的终端）：

```shell
git rebase --interactive OTHER-BRANCH-NAME
```

## 在某一时间点上重新定基提交

要对当前分支中最近的几个提交进行变基，可以在命令行中输入以下命令：

```shell
git rebase --interactive HEAD~7
```

## 变基时可用的命令

变基时有六个命令可用：

<dl>
<dt><code>pick</code></dt>
<dd>
<code>pick</code> 只表示包含提交。 在进行变基时，重新排列 <code>pick</code> 命令的顺序会更改提交的顺序。 如果选择不包含提交，应删除整行。 </dd>

<dt><code>reword</code></dt>
<dd>
<code>reword</code> 命令类似于 <code>pick</code>，但在使用后，变基过程就会暂停，让你有机会改变提交消息。 提交所做的任何更改都不受影响。 </dd>

<dt><code>edit</code></dt>
<dd>如果选择<code>edit</code>提交，你将有机会修改该提交，也就是说，你可以完全添加或更改整个提交。 在继续变基之前，您也可以进行更多提交。 这样您可以将一个大的提交记录拆分为多个较小的提交记录，或者删除在提交记录中执行的不正确的更改。 </dd>

<dt><code>squash</code></dt>
<dd>此命令可用于将两个或以上的提交合并为一个。 上面的提交被压缩进其下面的提交。 Git 让您有机会编写描述两次更改的新提交消息。</dd>

<dt><code>fixup</code></dt>
<dd>这类似于 <code>squash</code>，但将要合并的提交将丢弃其信息。 提交简单地合并到上面的提交中，并使用之前提交的信息来描述这两个更改。</dd>

<dt><code>exec</code></dt>
<dd>这使您能够对提交记录运行任意的 shell 命令。</dd>
</dl>

## 使用 `git rebase` 的示例

无论使用哪个命令，Git 都将启动[默认文本编辑器](/zh/enterprise-server@3.22/get-started/git-basics/associating-text-editors-with-git)，并且打开一个文件，其中详细说明了所选范围的提交信息。 该文件看起来像这样：

```text
pick 1fc6c95 Patch A
pick 6b2481b Patch B
pick dd1475d something I want to split
pick c619268 A fix for Patch B
pick fa39187 something to add to patch A
pick 4ca2acc i cant' typ goods
pick 7b36971 something to move before patch B

# Rebase 41a72e6..7b36971 onto 41a72e6
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#
```

从上到下分解此信息，我们可以看出：

* 列出了七个命令，表示从起点到当前分支状态之间有七处更改。
* 您选择要变基的提交按从最早更改（顶部）到最新更改（底部）的顺序排序。
* 每行列出一个命令（默认为 `pick`）、提交 SHA 和提交消息。 整个 `git rebase` 过程以这三列的操作为中心。 你所做的更改会被重新基变到你的存储库中。
* 提交完成后，Git 会告知正在处理的提交范围 (`41a72e6..7b36971`)。
* 最后，Git 会提供一些帮助，告知在变基提交时可用的命令。

## 其他阅读材料

* [在命令行中使用 Git rebase](/zh/enterprise-server@3.22/get-started/using-git/using-git-rebase-on-the-command-line)
* *Pro Git 书籍中的“Git 分支”一章*
* *Pro Git 书籍中的“交互式变基”一章*
* [使用变基压缩提交](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html)
* GitHub Desktop 文档中的 [在 GitHub Desktop 中同步分支](/zh/desktop/working-with-your-remote-repository-on-github-or-github-enterprise/syncing-your-branch-in-github-desktop)