Branching

Git Cherry-Pick

Cherry-Picking Commits

Git cherry-pick applies specific commits to another branch.

Understanding Git Cherry-Pick

Git cherry-pick is a powerful command that allows you to select specific commits from one branch and apply them onto another branch. This is particularly useful when you want to apply bug fixes, features, or any specific changes without merging the entire branch.

Unlike a merge or rebase, which typically involves a sequence of commits, cherry-pick is used to extract individual commits.

When to Use Git Cherry-Pick

Cherry-picking is useful in scenarios such as:

  • Bug Fixes: You have fixed a bug in one branch and need to apply that fix to another branch.
  • Selective Feature Application: You want to apply a specific feature or change from a feature branch to the main branch.
  • Isolated Changes: You need certain changes without merging all the changes from a branch.

How to Cherry-Pick a Commit

To cherry-pick a commit, you first need to get the commit hash of the commit you want to apply. Follow these steps:

Example of Cherry-Picking a Commit

Suppose you have a bug fix commit on a branch named bug-fix and you want to apply it to the main branch. Here's how you can do it:

Resolving Conflicts During Cherry-Pick

Sometimes, cherry-picking a commit can result in conflicts, especially if the commit modifies a file that has changed in the target branch. To resolve conflicts, follow these steps:

  • Git will pause the cherry-pick process and mark the conflicts in the files.
  • Open the affected files and resolve the conflicts manually.
  • Once resolved, mark the files as resolved using:

Conclusion

Git cherry-pick is a versatile tool in your Git toolkit that allows you to apply specific commits across branches efficiently. By understanding its usage and handling conflicts, you can manage your codebase effectively.

In the next post, we will explore how to delete branches in Git, ensuring your repository remains organized and clean.

Previous
Rebase