new-branch
recent
commit
git

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

Interview Questions practice on Codemia

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

Browse interview questions

To move the most recent commit(s) to a new branch in Git, you can use the following steps. This process involves creating a new branch from the current state, resetting the original branch to remove the commit(s), and then switching to the new branch.

Step-by-Step Guide

  1. Create a New Branch from the Current Commit:
    First, create a new branch that points to the current commit (which includes the commit(s) you want to move):
bash
 git branch new-branch-name

Replace new-branch-name with the desired name of your new branch.

  1. Reset the Original Branch to Remove the Commit(s):
    Next, reset your current branch to the point before the commit(s) you want to move. If you're moving just the most recent commit, use:
bash
 git reset --hard HEAD~1

If you're moving more than one commit, replace HEAD~1 with HEAD~N, where N is the number of commits you want to move. For example, to move the last 3 commits:

bash
git reset --hard HEAD~3

Warning: The --hard option will discard any uncommitted changes in your working directory. Make sure you've committed or stashed any changes you want to keep before running this command.

  1. Switch to the New Branch:
    Now, you can switch to the new branch where the commits are preserved:
bash
 git checkout new-branch-name

Example Workflow

Let's say you made a commit on the main branch, but then realized that commit belongs on a different branch. Here's what you would do:

  1. Create the new branch from the current commit:
bash
 git branch feature-branch
  1. Reset the main branch to remove the commit:
bash
 git reset --hard HEAD~1
  1. Switch to the new branch where the commit has been preserved:
bash
 git checkout feature-branch

Summary

  • Step 1: Create a new branch from the current commit with git branch.
  • Step 2: Reset the original branch to remove the commit(s) with git reset --hard.
  • Step 3: Switch to the new branch with git checkout.

This process effectively moves your recent commits to a new branch while keeping your original branch clean.


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.