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.).

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github