Copying commits from one branch to another can primarily be achieved using two Git commands: git cherry-pick and git rebase.
1. Using git cherry-pick
The git cherry-pick command applies a specific commit from one branch to another. It is particularly useful when you need to copy only a few specific commits. The steps are as follows:
-
Switch to the target branch: First, switch to the branch where you intend to copy the commits. For instance, if you want to copy commits to the
masterbranch, you should first switch tomaster.bashgit checkout master -
Use the
git cherry-pickcommand: Next, use thegit cherry-pickcommand with the hash of the commit you wish to copy. For example, if the commit hash isabc123, the command is:bashgit cherry-pick abc123If multiple commits need to be copied, list all hashes consecutively:
bashgit cherry-pick abc123 def456 -
Resolve conflicts (if any): During the
cherry-pickprocess, conflicts may occur. Git will pause the operation, allowing you to manually resolve conflicts. After resolving conflicts, usegit addto mark the resolved files, and then continue withgit cherry-pick --continue.
2. Using git rebase
If you aim to copy a series of consecutive commits or to reorganize your commit history, git rebase is often preferable. You can use the git rebase command for interactive rebasing to selectively copy commits to a new branch. The steps are as follows:
-
Switch to the source branch: First, switch to the branch containing the commits you wish to copy.
bashgit checkout feature-branch -
Use the
git rebasecommand for interactive rebasing: Then, initiate an interactive rebase process where you can select (using commands such aspick,drop,squash, etc.) which commits to copy or modify.bashgit rebase -i masterThis will open an editor listing all commits to be rebased, allowing you to modify them.
-
Resolve conflicts and complete the rebase: Similar to
cherry-pick, the rebase process may encounter conflicts. After resolving conflicts, usegit addto add the modified files, and then complete the rebase withgit rebase --continue.
Summary
Both methods have their advantages: git cherry-pick is ideal for copying a few specific commits, whereas git rebase is better suited for copying a series of consecutive commits and reorganizing the commit history. In practice, the choice depends on your specific requirements and context.