63

How can I apply part of a commit from one branch to another? I understand that I can cherry-pick a commit, but I need to go one step further and "cherry pick" some of the changes introduced by that commit and apply them to another (target) branch.

Is there a clean way to do this, or should I just apply the entire commit, manually undo some hunks, and remember to create more atomic commits in the future?

1

2 Answers 2

92

git cherry-pick -n <SHA> will stage the changes but not commit them. You can then use git reset -p to unstage the bits you don't want, or git reset HEAD and git add -Ap to stage only the changes you want.

1
  • 1
    applying the 'git cherry-pick -n <SHA>' and then typing git status will also offer a description on how to dismiss the files of the cherry-picked commit, that you would like to reset.
    – Simeon
    Feb 5, 2021 at 10:57
16

If the parts you want to apply can be specified by path (i.e., you do not wish to specify hunks within one file) another solution is possible.

One approach is to form a patch from the commit, and apply it to your branch.

With the branch you wish to modify checked out:

git show <SHA> -- <relevant paths> | git apply

Will apply any changes in commit SHA, in paths relevant paths to your current working copy.

1
  • 2
    I tried this but all lines said "patch does not apply"
    – Andy Ray
    Sep 23, 2014 at 18:24

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.