Move the most recent commit(s) to a new branch with Git

 

To move the most recent commit(s) to a new branch in Git, you can follow these steps:

  1. Create a New Branch: First, create a new branch from the current branch. This new branch will be the destination for the most recent commit(s). You can do this with the git branch command:

    bash
  • git branch new-branch-name
  • Switch to the New Branch: Use the git checkout command to switch to the newly created branch:

    bash
  • git checkout new-branch-name
  • Apply the Commits: If you want to move only the most recent commit, you can use git cherry-pick to apply it to the new branch. If you want to move multiple commits, you can specify a range of commits using git cherry-pick. For example, to move the last three commits:

    bash
  • git cherry-pick HEAD~3..HEAD

    This will apply the last three commits from the current branch to the new branch.

  • Remove the Commits from the Original Branch: Optionally, if you want to remove the commits from the original branch, you can use the git reset command:

    bash
    1. git reset HEAD~3

      This will reset the original branch's HEAD to a previous commit, effectively removing the last three commits.

    Here's an example that demonstrates how to move the most recent commit(s) to a new branch:

    bash
    # Create a new branch git branch new-feature # Switch to the new branch git checkout new-feature # Cherry-pick the last three commits from the current branch git cherry-pick HEAD~3..HEAD # Optionally, reset the current branch to remove the last three commits git checkout original-branch git reset HEAD~3

    In this example, we created a new branch called new-feature, switched to it, and cherry-picked the last three commits from the original branch. The original-branch was then reset to remove those commits, effectively moving them to the new-feature branch.

    Be cautious when using git reset as it rewrites history. If your commits have already been pushed to a remote repository, this can cause issues for other collaborators.

    Comments