Move the Most Recent Commit(s) to a New Branch with Git

Better Stack Team
Updated on June 24, 2024

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

Step 1: Create a New Branch

First, create a new branch at the current commit:

 
git branch new-branch-name

This command creates a new branch named new-branch-name that points to the current commit.

Step 2: Switch to the New Branch

Switch to the newly created branch:

 
git checkout new-branch-name

Or, if you're using Git version 2.23 or later, you can combine steps 1 and 2 using the -b option:

 
git checkout -b new-branch-name

This command creates a new branch named new-branch-name and switches to it.

Step 3: Reset the Original Branch

Now, reset the original branch (the one you were previously on) to the commit before the one you want to move:

 
git reset --hard HEAD~1

This command moves the HEAD of the original branch to the previous commit (HEAD~1) and discards any changes made in the most recent commit.

Note:

  • Be careful when using git reset --hard, as it will discard any changes made in the most recent commit(s) and reset the working directory to the state of the specified commit.
  • If you have multiple recent commits to move to the new branch, you can adjust the number in the HEAD~1 command to match the number of commits you want to move (HEAD~2, HEAD~3, etc.).