Move the most recent commit(s) to a new branch with Git
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
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
- 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):
Replace new-branch-name with the desired name of your new branch.
- 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:
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:
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.
- Switch to the New Branch:Now, you can switch to the new branch where the commits are preserved:
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:
- Create the new branch from the current commit:
- Reset the
mainbranch to remove the commit:
- Switch to the new branch where the commit has been preserved:
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.

