git cherry-pick命令的使用

发布时间:2026/7/2 3:06:59
git cherry-pick命令的使用 们以一个文件夹为例演示一次git cherry-pick的作用。之所以不使用.txt文件编辑内容来演示是因为git cherry-pick执行的时候会把某次commit涉及到的上下文也合并回主分支。所以如果用.txt文件编辑来演示则最后挑选commit2合并回主分支的时候commit1作为commit2的上下文也会被合并回去就达不到演示的效果。现在主分支上有一个文件test_cherry-pick_main.txt接着开始操作新建一个分支命名为“test_cherry-pick”并确认已切换到test_cherry-pick分支1 PS D:\Project\Test\TestGitCommands git branch test_cherry-pick 2 PS D:\Project\Test\TestGitCommands git branch 3 * main 4 test_cherry-pick 5 test_stash 6 PS D:\Project\Test\TestGitCommands git checkout test_cherry-pick 7 Switched to branch test_cherry-pick 8 PS D:\Project\Test\TestGitCommands git branch 9 main 10 * test_cherry-pick 11 test_stash在test_cherry-pick分支上增加内容假设在开发新功能1新增一个文件test_cherry-pick_func1.txt然后将这次的改动提交1 PS D:\Project\Test\TestGitCommands git add test_cherry-pick/test_cherry-pick_func1.txt 2 PS D:\Project\Test\TestGitCommands git status 3 On branch test_cherry-pick 4 Changes to be committed: 5 (use git restore --staged file... to unstage) 6 new file: test_cherry-pick/test_cherry-pick_func1.txt 7 8 PS D:\Project\Test\TestGitCommands git commit -a -m add func1 9 [test_cherry-pick 6a62df8] add func1 10 1 file changed, 0 insertions(), 0 deletions(-) 11 create mode 100644 test_cherry-pick/test_cherry-pick_func1.txt 12 PS D:\Project\Test\TestGitCommands git status 13 On branch test_cherry-pick 14 nothing to commit, working tree clean接着再增加内容假设在开发新功能2提交1 PS D:\Project\Test\TestGitCommands git add test_cherry-pick/test_cherry-pick_func2.txt 2 PS D:\Project\Test\TestGitCommands git status 3 On branch test_cherry-pick 4 Changes to be committed: 5 (use git restore --staged file... to unstage) 6 new file: test_cherry-pick/test_cherry-pick_func2.txt 7 8 PS D:\Project\Test\TestGitCommands git commit -a -m add func2 9 [test_cherry-pick 2ff16c4] add func2 10 1 file changed, 0 insertions(), 0 deletions(-) 11 create mode 100644 test_cherry-pick/test_cherry-pick_func2.txt 12 PS D:\Project\Test\TestGitCommands git status 13 On branch test_cherry-pick 14 nothing to commit, working tree clean接着我们就可以回到主分支将第二次commit的内容合并回主分支了。在切回主分支之前先查看一下当前分支的提交记录找到第二次commit的哈希值commitHash1 PS D:\Project\Test\TestGitCommands git log --oneline 2 2ff16c4 (HEAD - test_cherry-pick) add func2 3 6a62df8 add func1得到第二次提交的commitHash是2ff16c4最后就可以切回主分支使用git cherry-pick将第二次提交合并回主分支1 PS D:\Project\Test\TestGitCommands git checkout main 2 Switched to branch main 3 Your branch is up to date with origin/main. 4 PS D:\Project\Test\TestGitCommands git branch 5 * main 6 test_cherry-pick 7 test_stash可以看到文件夹恢复到了主分支的状态然后执行git cherry-pick1 PS D:\Project\Test\TestGitCommands git cherry-pick 2ff16c4 2 [main c90085e] add func2 3 Date: Wed Apr 29 15:37:52 2026 0800 4 1 file changed, 0 insertions(), 0 deletions(-) 5 create mode 100644 test_cherry-pick/test_cherry-pick_func2.txt可以看到主分支上只新增了test_cherry-pick_func2.txt文件说明只把test_cherry-pick分支的第二次commit的内容合并过来了主分支。