If you don't want to merge an entire branch, you can choose to merge specific commits... a process called cherry-picking.
Let's look at one scenario when cherry-picking is useful. Let's say you've been working on a feature branch and decide that most of the work is not good. You want to abandon the branch, but there are one or more commits that are good. You don't want to lose that work, so you can cherry-pick the specific commits that are good, applying them to a different branch.
Cherry Pick a Commit from a Different Branch
- In your terminal (Terminal, Git Bash, or Windows Command Prompt), navigate to the folder that is your Git repo.
- Check out the branch you want to work on (not the one with the commit). Enter this command (if needed, replaced master with your desired branch):
- git checkout master
- Each commit has a unique hash (which looks something like 2f5451f). You need to find the hash for the commit you want to cherry-pick. Here are two places you can see the hash for commits:
- In the commit history on the GitHub or Bitbucket or website.
- In your terminal (Terminal, Git Bash, or Windows Command Prompt) run the command git log --oneline
- Once you know the hash for the good commit you want to cherry-pick, run the following command (replacing 2f5451f with your commit's hash):
- git cherry-pick 2f5451f
|Cherry Pick Multiple Commits|
You can cherry-pick multiple commits by listing multiple hashes in the order they were originally committed.
git cherry-pick hash1 hash5 hash7
Go Beyond Git
We offer the best coding courses and bootcamps for students at all levels of experience. Classes are hands-on and students receive workbooks with step-by-step instructions through exercises with real-world applications. Check out our programming courses now: