In this tutorial, we will learn how to cherry-pick commits in Git, a powerful tool that allows developers to selectively apply changes from one branch to another. This can be particularly useful when you want to apply some but not all changes, that have been made in a different branch.
By the end of this tutorial, you will:
- Understand what cherry-pick is and why it can be useful.
- Be able to use cherry-pick to apply changes from one branch to another.
- Learn how to revert commits when necessary.
Prerequisites:
You should have Git installed and have a basic understanding of how to commit changes.
cherry-pickCherry-pick is a git command that allows you to apply changes from specific commits. This is in contrast to merging or rebasing, where all changes from one branch are applied to another.
cherry-pickTo use cherry-pick, you first need the commit hash of the commit you want to apply. This can be found by using git log.
git checkout <branch-name>cherry-pick command with the commit hash:git cherry-pick <commit-hash>cherry-pickgit checkout masterUse git log to find the commit hash.
git log
This will show you a list of all commits, with the most recent at the top. Each commit will have a hash next to it. Copy the hash of the commit you want to cherry-pick.
Use git cherry-pick with the commit hash.
git cherry-pick 9fceb02
This will apply the changes from commit 9fceb02 to the master branch.
If you make a mistake or change your mind, you can always undo a cherry-pick with the --abort option:
git cherry-pick --abort
This will stop the current cherry-pick process and return you to the state before you started the cherry-pick.
In this tutorial, we've covered how to use Git's cherry-pick feature to selectively apply changes from one branch to another, and how to revert commits when necessary.
From here, you can further your understanding by learning about other powerful features of Git, such as rebase and merge.
To solidify your understanding, try these exercises on your own.
Exercise 1: Cherry-pick a commit from one branch to another in a new project.
Exercise 2: Create a situation where cherry-picking would be useful, then use it to solve the problem.
Exercise 3: Cherry-pick multiple commits at once.
Note: Remember to use git log to view your commit history and git cherry-pick --abort if you need to undo a cherry-pick.