git cherry-pick的使用 提取其次提交到别一个分支

概述

git cherry-pick可以理解为”挑拣”提交,它会获取某一个分支的单笔提交,并作为一个新的提交引入到你当前分支上。 当我们需要在本地合入其他分支的提交时,如果我们不想对整个分支进行合并,而是只想将某一次提交合入到本地当前分支上,那么就要使用git cherry-pick了。
用法

git cherry-pick [<options>] <commit-ish>...

常用options:
    --quit                退出当前的chery-pick序列
    --continue            继续当前的chery-pick序列
    --abort               取消当前的chery-pick序列,恢复当前分支
    -n, --no-commit       不自动提交
    -e, --edit            编辑提交信息

git cherry-pick commitid

在本地仓库中,有两个分支:branch1和branch2,我们先来查看各个分支的提交:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

# 切换到branch2分支

$ git checkout branch2

Switched to branch 'branch2'

# 查看最近三次提交

$ git log --oneline -3

23d9422 [Description]:branch2 commit 3

2555c6e [Description]:branch2 commit 2

b82ba0f [Description]:branch2 commit 1

# 切换到branch1分支

$ git checkout branch1

Switched to branch 'branch1'

# 查看最近三次提交

$ git log --oneline -3

20fe2f9 commit second

c51adbe commit first

ae2bd14 commit 3th

现在,我想要将branch2分支上的第一次提交内容合入到branch1分支上,则可以使用git cherry-pick命令:

1

2

3

4

5

$ git cherry-pick 2555c6e

error: could not apply 2555c6e... [Description]:branch2 commit 2

hint: after resolving the conflicts, mark the corrected paths

hint: with 'git add <paths>' or 'git rm <paths>'

hint: and commit the result with 'git commit'

cherry-pick时,没有成功自动提交,这说明存在冲突,因此首先需要解决冲突,解决冲突后需要git commit手动进行提交:

1

2

3

4

5

git commit 

[branch1 790f431] [Description]:branch2 commit 2

 Date: Fri Jul 13 18:36:44 2018 +0800

 1 file changed, 1 insertion(+)

 create mode 100644 only-for-branch2.txt

或者git add .后直接使用git cherry-pick --continue继续。
现在查看提交信息:

1

2

3

4

git log --oneline -3

790f431 [Description]:branch2 commit 2

20fe2f9 commit second

c51adbe commit first

branch2分支上的第二次提交成功合入到了branch1分支上。

以上就是git cherry-pick的基本用法,如果没有出现冲突,该命令将自动提交。
git cherry-pick -n

如果不想git cherry-pick自动进行提交,则加参数-n即可。比如将branch2分支上的第三次提交内容合入到branch1分支上:

1

2

3

4

git cherry-pick 23d9422

[branch1 2c67715] [Description]:branch2 commit 3

 Date: Fri Jul 13 18:37:05 2018 +0800

 1 file changed, 1 insertion(+)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值