git cherry-pick command
If you want to move the code from one branch to another branch, the common practice is the merge
or rebase
instruction, but if you want to move a commit (or some) of a branch to another branch, you need to use the cherry-pick
instruction .
Article directory
1. Transfer a commit
master
For example, there are , feature-new
and feature-old
branches in the warehouse , as shown in the following figure:
Now want to feature-old
apply the G commit of branch to feature-new
branch. Execute the following command:
# 假设现在在master分支
# 从master分支切换到feature-new(要接收别的分支某次提交转移的分支)
git checkout feature-new
# 执行转移操作:git cherry-pick <commitHash>
git cherry-pick G
After executing the above command, the code base is as shown below:
That is , a new commit G was added to the endfeature-new
of the branch .
Note: cherry-pick
The parameter of the instruction does not have to be the hash value of the commit, and the branch name is also acceptable, indicating that the latest commit of the branch is transferred , as follows:
# 将feature-old分支的最新一次提交H转移到当前分支
git cherry-pick feature-old
2. Transfer some commits
git cherry-pick <commitHashA> <commitHashA>
The above command applies two commits A and B to the current branch, which results in two corresponding new commits on the current branch.
If you want to transfer a series of consecutive commits, you can use the following shorthand syntax:
git cherry-pick A..B
The above command can transfer all commits from A to B , they must be placed in the correct order: commit A must be earlier than commit B, otherwise the command will fail with no error.
Note: With the above command, commit A will not be included cherry-pick
in . If you want to include commit A, you can use the following syntax:
git cherry-pick A^..B
3. Code conflict
3.1 --continue
git cherry-pick --continue
After the user resolves the code conflict, first re-add the modified file to the temporary storage area ( git add .
), and then use the above command to let the cherry-pick
process continue.
3.2 --abort
git cherry-pick --abort
After a code conflict, abort the merge and go back to the way it was before the operation.
3.3 --quit
git cherry-pick --quit
After a code conflict, exit cherry-pick
, but do not return to the way it was before the operation.