git: Apply commit to another branch

2 min read

When we have a change (commit) that we want to apply to several branches we can use git cherry-pick.

To do so we just need to specify the commit or set of commits like this:

git cherry-pick <COMMIT_ID>
git cherry-pick <COMMIT_ID>...<COMMIT_ID>

We can also cherry-pick without commiting using the --no-commit option (-n for short) so that the changes are applied but not commited:

git cherry-pick <COMMIT_ID> -n
git cherry-pick <COMMIT_ID>...<COMMIT_ID> -n

Obviously we can came across some merging conflicts that we might need to resolve:

$ git cherry-pick -n 0ed7469cbe395da2bbd8cf62e6c8cbef30a37832
Auto-merging main.tf
Auto-merging locals.tf
CONFLICT (content): Merge conflict in locals.tf
Auto-merging CHANGELOG.md
CONFLICT (content): Merge conflict in CHANGELOG.md
error: could not apply 0ed7469... Added button for publishing a poll
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'

In case you needed to cherry-pick a merge instead of a commit, we can also use the -m flag:

git cherry-pick -m 1 <MERGE_COMMIT_ID> 

Posted on 26/04/2021

Categories