乐闻世界logo
搜索文章和话题

How to Copy Commits from One Branch to Another in Git?

2024年7月4日 00:15

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:

  1. 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 master branch, you should first switch to master.

    bash
    git checkout master
  2. Use the git cherry-pick command: Next, use the git cherry-pick command with the hash of the commit you wish to copy. For example, if the commit hash is abc123, the command is:

    bash
    git cherry-pick abc123

    If multiple commits need to be copied, list all hashes consecutively:

    bash
    git cherry-pick abc123 def456
  3. Resolve conflicts (if any): During the cherry-pick process, conflicts may occur. Git will pause the operation, allowing you to manually resolve conflicts. After resolving conflicts, use git add to mark the resolved files, and then continue with git 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:

  1. Switch to the source branch: First, switch to the branch containing the commits you wish to copy.

    bash
    git checkout feature-branch
  2. Use the git rebase command for interactive rebasing: Then, initiate an interactive rebase process where you can select (using commands such as pick, drop, squash, etc.) which commits to copy or modify.

    bash
    git rebase -i master

    This will open an editor listing all commits to be rebased, allowing you to modify them.

  3. Resolve conflicts and complete the rebase: Similar to cherry-pick, the rebase process may encounter conflicts. After resolving conflicts, use git add to add the modified files, and then complete the rebase with git 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.

标签:Git