Sobes.tech
Middle

What is the purpose of the git cherry-pick command?

sobes.tech AI

Answer from AI

For transferring individual commits from one branch to another. Allows selectively applying changes presented by a specific commit without the need to merge the entire branch.

Advantages:

  • Isolated application of changes.
  • Avoidance of merge conflicts when transferring only the necessary commits.
  • Maintaining a clean branch history.

Syntax:

git cherry-pick <commit-hash>

You can specify multiple commit hashes or a range of commits:

git cherry-pick <commit-hash-1> <commit-hash-2> ...
git cherry-pick <start-hash>^..<end-hash>

Usage example:

Suppose there is a feature branch with commits A, B, C, and a develop branch. You need to transfer only commit B to develop.

  1. Switch to the develop branch:
    git checkout develop
    
  2. Perform cherry-pick for commit B (assuming its hash is abcdef):
    git cherry-pick abcdef
    

If conflicts occur, resolve them, then continue (git cherry-pick --continue) or abort the operation (git cherry-pick --abort).

Alternatives:

  • git merge: Merges all changes from one branch into another.
  • git rebase: Moves or combines a sequence of commits onto a new base commit.

git cherry-pick is useful when you need to selectively transfer bug fixes or small functional changes between branches.