git cherry-pick 同步修改到另一个分支
我们在开发中有时会遇到,需要将另一个分支部分修改同步到当前分支。
如下图,想把 devA 分支中 commit E 和 F,同步到下面绿色的 devB 分支中。
这时候就可以使用 git cherry-pick
来完成这项任务。
(cherry-pick 有筛选、精选的意思)
一、基本用法#
转移单个提交
git cherry-pick <commitHash>
# 切换到 devB 分支
$ git checkout devB
# Cherry pick 操作
$ git cherry-pick <HashE>
解决冲突后,commit 即可
二、转移多个提交#
如果我有一堆连续的 commit 都想同步过去,那么可以用下面的语法:
下面的命令可以转移从 E 到 F 的所有 commit。 注意按顺序写:提交 E 必须早于提交 F
git cherry-pick <HashE>..<HashF>
还要注意上面命令是左开右闭的,即不包含 commit_E,如果需要两边都包括,用下面的语法:
git cherry-pick <HashE>^..<HashF>
如果是分开的几个 commit,可以这样写:
git cherry-pick <HashE> <HashG>
三、参数#
文档中是这样写的:
usage: git cherry-pick [<options>] <commit-ish>...
or: git cherry-pick <subcommand>
--quit end revert or cherry-pick sequence
--continue resume revert or cherry-pick sequence
--abort cancel revert or cherry-pick sequence
--skip skip current commit and continue
--cleanup <mode> how to strip spaces and #comments from message
-n, --no-commit don't automatically commit
-e, --edit edit the commit message
-s, --signoff add a Signed-off-by trailer
-m, --mainline <parent-number>
select mainline parent
--rerere-autoupdate update the index with reused conflict resolution if possible
--strategy <strategy>
merge strategy
-X, --strategy-option <option>
option for merge strategy
-S, --gpg-sign[=<key-id>]
GPG sign commit
-x append commit name
--ff allow fast-forward
--allow-empty preserve initially empty commits
--allow-empty-message
allow commits with empty messages
--keep-redundant-commits
keep redundant, empty commits
提几个会用得到的:
1)-n
如果你想转移多个 commit 并在新分支中只想有一个 commit,那就可以添加 -n
参数,不自动提交代码,都转移后一次性手动提交。(注意如果有 conflict 情况就不是很好用)(为了分辨是从其他分支转移过来的,可以新开一个分支同步这些 commit,然后再 merge 到目标分支)
-n, --no-commit don't automatically commit
2)-x
在提交信息的末尾追加一行(cherry picked from commit ...),方便以后查到这个提交是如何产生的。
-x append commit name
3)不建议同步「合并(merge)节点」,得到的结果应该不是你想要的(有兴趣可以自己尝试)。
四、代码冲突#
1)--continue
同步代码不可避免遇到冲突情况,解决冲突后,将修改的文件重新加入暂存区 git add .
,然后使用下面命令继续:
git cherry-pick --continue
2)--abort
处理过程中可能有误操作,那么可以放弃合并,回到操作前的样子。
git cherry-pick --abort
(3)--quit
发生代码冲突后,退出 cherry pick,但是不回到操作前的样子。
git cherry-pick --quit
作者:王小皮
出处:https://www.cnblogs.com/shuofxz/p/16994923.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
叮咚:点个赞再走吧
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异