git
version control
branching
commits
tutorial

git how to move some commits to new branch

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Understanding Git: Moving Commits to a New Branch

Git is an essential tool for managing, tracking, and collaborating on software projects. One common task in Git is to manage commits, particularly when you want to move some of them to a new branch. This operation can help in organizing your work, isolating features, or maintaining a clean history. In this article, we will explore the process of moving commits to a new branch, with technical explanations and examples.

Git Branching and Commits

In Git, a branch represents a line of development. By default, a new Git repository has a branch named main or master. Branching allows developers to work on different features or bug fixes independently. Each commit in Git is like a snapshot of your changes at a point in time.

Scenario: Moving Commits to a New Branch

Imagine you've been working on the main branch but realize you need to separate a sequence of commits into a feature branch. Moving commits involves creating a new branch and then changing the commit history to reflect that these commits belong to this new branch.

The operation can be broken down into a few steps:

  1. Identify the Commits to Move:
    • Use git log to view the history and identify the commits to move.
  2. Create a New Branch:
    • Use git branch or git checkout -b to create a new branch.
  3. Use Git Rebase or Git Cherry-Pick:
    • Employ git rebase or git cherry-pick to move commits to the new branch.

Step-by-Step Guide

Step 1: Identify the Commits

First, identify the range of commits you want to move. You can do this by running:

  • Merge Conflicts: When moving commits, you might encounter conflicts. Git will notify you, and you will need to resolve them before continuing.
  • Data Loss Risk: Resetting a branch removes changes. Ensure you have backups or are confident in the operation.
  • Rebase vs. Cherry-Pick: Choosing between these depends on whether you want to retain commit history or apply only specific changes.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.