Cherry Pick Example
(this post if part of the material I cover in my devops course)
Here's an example of the git cherry-pick command.
main branch
- create a new git repository called cherry
1$> mkdir cherry
2$> cd cherry/
3$> git init
4hint: Using 'master' as the name for the initial branch. This default branch name
5....
6...
7Initialized empty Git repository in /home/osboxes/cherry/.git/
- add a file called one.txt and add 3 lines to it, each line in its own commit, in branch main
1$> git checkout -b main
2Switched to a new branch 'main'
3$> echo 11111 > one.txt
4$> git add one.txt
5$> git commit -m "line 1 in branch main"
6[main (root-commit) c44d780] line 1 in branch main
71 file changed, 1 insertion(+)
8create mode 100644 one.txt
9$> echo 22222 >> one.txt
10$> git add one.txt
11$> git commit -m "line 2 in branch main"
12[main 28cfbbf] line 2 in branch main
131 file changed, 1 insertion(+)
14$> echo 33333 >> one.txt
15$> git add one.txt
16$> git commit -m "line 3 in branch main"
17[main 794732c] line 3 in branch main
181 file changed, 1 insertion(+)
19$>
feature branch
- Now we do:
- create a new branch called feature
- add 3 commits, that add 3 lines ('xxxxx', 'yyyyyy', 'zzzzzz') (note that 3 lines are not consecutive, so that git can locate each one)
1$>
2$> git checkout -b feature
3Switched to a new branch 'feature'
4$> vi one.txt
5$> git add one.txt
6$> git commit -m "adding xxxxx"
7[feature 7698294] adding xxxxx
8 1 file changed, 1 insertion(+)
9$> vi one.txt
10$> git add one.txt
11$> git commit -m "adding yyyyy"
12[feature 0c61cdc] adding yyyyy
13 1 file changed, 1 insertion(+)
14$> vi one.txt
15$> git add one.txt
16$> git commit -m "adding zzzzz"
17[feature 02787b3] adding zzzzz
18 1 file changed, 1 insertion(+)
19$> cat one.txt
2011111
21xxxxxxx
2222222
23yyyyy
2433333
25zzzzz
26$>
git cherry-pick
- get commit sha codes from feature branch (just the 'yyyyy' commit)
1$> git checkout feature
2Switched to branch 'feature'
3$> git log --oneline
402787b3 (HEAD -> feature) adding zzzzz
50c61cdc adding yyyyy
67698294 adding xxxxx
7794732c (main) line 3 in branch main
828cfbbf line 2 in branch main
9c44d780 line 1 in branch main
10$>
- go back to main branch, and use git cherry-pick command to get only the 'yyyyy' commit
1$>
2$> git checkout main
3Switched to branch 'main'
4$> cat one.txt
511111
622222
733333
8$> git log --oneline
9794732c (HEAD -> main) line 3 in branch main
1028cfbbf line 2 in branch main
11c44d780 line 1 in branch main
12$>
13$> git checkout main
14Switched to branch 'main'
15$>
16$> git cherry-pick 0c61cdc
17Auto-merging one.txt
18[main eb92b88] adding yyyyy
19 Date: Sun May 26 10:01:01 2024 -0400
20 1 file changed, 1 insertion(+)
21$>
22$> git status
23On branch main
24nothing to commit, working tree clean
25$> git log --oneline
26eb92b88 (HEAD -> main) adding yyyyy
27794732c line 3 in branch main
2828cfbbf line 2 in branch main
29c44d780 line 1 in branch main
30$> cat one.txt
3111111
3222222
33yyyyy
3433333
35$>