Skip to content
← 返回Git列表
Git任务与配置

Git 合并与撤销 ​

合并、变基与补丁 ​

git cherry-pick · 将现有提交的变更应用到当前分支 ​

如需应用到其他分支,请先用 git checkout 切换到目标分支。 更多信息:https://git-scm.com/docs/git-cherry-pick。

  • 将单个提交应用到当前分支:
bash
git cherry-pick {{提交哈希}}
  • 将连续多个提交应用到当前分支(也可参考 git rebase --onto):
bash
git cherry-pick {{起始提交}}~..{{结束提交}}
  • 将多个(非连续的)提交应用到当前分支:
bash
git cherry-pick {{提交1 提交2 ...}}
  • 将提交变更应用到工作区但不自动创建提交:
bash
git cherry-pick {{[-n|--no-commit]}} {{提交哈希}}

git merge · 合并分支 ​

更多信息:https://git-scm.com/docs/git-merge。

  • 将指定分支合并到当前分支:
bash
git merge {{分支名}}
  • 编辑合并说明信息:
bash
git merge {{[-e|--edit]}} {{分支名}}
  • 合并分支,创建合并提交:
bash
git merge --no-ff {{分支名}}
  • 遇到冲突时中止合并:
bash
git merge --abort
  • 采用特定的策略进行合并:
bash
git merge {{[-s|--strategy]}} {{策略}} {{[-X|--strategy-option]}} {{策略选项}} {{分支名}}

git rebase · 在新基点上逐个重放提交 ​

变基通常会为重放的提交生成新哈希,不是创建一个合并提交。已共享分支先确认协作约定。 更多信息:https://git-scm.com/docs/git-rebase。

  • 把当前分支独有的提交重放到目标分支之上:
bash
git rebase {{目标分支}}
  • 启动交互式变基,允许对提交的内容进行重新排序、省略、合并或修改:
bash
git rebase {{[-i|--interactive]}} {{目标分支或 commit 的 hash}}
  • 处理完冲突文件后,继续执行变基:
bash
git rebase --continue
  • 跳过当前整个提交的补丁,继续变基(该提交的其他改动也会被跳过):
bash
git rebase --skip
  • 终止正在执行中的变基(例如:对于正处于解决冲突中的任务,将其打断,恢复到变基前的状态):
bash
git rebase --abort
  • 把当前分支中旧基点之后的提交重放到新基点:
bash
git rebase --onto {{新基点}} {{旧基点}} {{待变基分支}}
  • 启动交互式变基,对最近提交的 5 个 commits 进行重新排序、省略、合并或修改:
bash
git rebase {{[-i|--interactive]}} HEAD~5
  • 对可由策略选项处理的冲突,优先采用正在重放的提交一侧;变基中的 theirs 指原工作分支,仍须审阅结果:
bash
git rebase {{[-X|--strategy-option]}} theirs {{分支名称}}

撤销、恢复与清理 ​

git-revert · 新建一个反向提交来撤销已有提交,适合已经共享的历史。操作前确认工作区干净;合并提交需额外指定主线 ​

  • 撤销指定普通提交,并检查新提交:
bash
git revert {{commit-hash}}
  • 撤销最近一次提交:
bash
git revert HEAD
  • 冲突解决并暂存文件后继续:
bash
git revert --continue
  • 放弃正在进行的撤销,回到操作前状态:
bash
git revert --abort

示例整理自 tldr-pages,作者为 tldr-pages team and contributors,遵循 CC BY 4.0。

继续阅读