Git: Move Your Latest Commits to Another Branch

Tyler Tyler (258)
0

Sometimes we start writing code without managing our branches in advance. Then we make commits in master (or some other base branch) when we intended to carve off a new feature branch. In this guide, we'll learn how to move our latest commits to another branch, leaving our original branch unchanged.

Before we do anything, we need to assess the situation. Assuming you have checked out the branch that we're going to modify, we need to see the history.

Use git log to deteremine how many commits to move.

git log

You'll see output similar to this:

commit 5576dbf62182ac1d263e9777e31ff7f35ac6eee3 (HEAD -> master)
Author: Tyler <tyler@email.com>
Date:   Fri Nov 8 12:04:42 2019 -0800

    Another commit to move

commit edec499e8c85adf8c6fd79bc1b6993bfb233a5a0
Author: Tyler <tyler@email.com>
Date:   Fri Nov 8 12:04:29 2019 -0800

    One commit to move

commit 896cfcd0ae55d95fa81915a60460948b40fa55fa (origin/master, origin/HEAD)
Author: Zach Levine <zach@email.com>
Date:   Thu Nov 7 10:40:13 2019 -0500

    Awesome code added to the repository.

We can see that that HEAD is two commits ahead of origin/HEAD, and these are the two commits we want to move to another branch.

In the remaining steps, we'll cover to how move these commits to a new branch or an existing branch.

The following steps will show you how to move your latest commits to a new branch.

Create a new branch
git branch feature/newbranch

This will create a new branch including all of the commits of the current branch.

Move the current branch back two commits
git reset --keep HEAD~2
Checkout the new branch
git checkout feature/newbranch

That's it! Your two latest commits have been removed from master (or your current branch), and they've been included in a new branch called feature/newbranch.

The following steps will show you how to move your latest commits to an existing branch. This is useful if you've been working out of a feature branch, but accidentally started making commits in the wrong branch.

We'll assume that the "current" branch, with the commits that need to be removed, is master.

Check out the existing branch
git checkout feature/existingbranch
Merge master
git merge master

This will add the additional commits to the existing branch.

Checkout master
git checkout master
Move the current branch back two commits
git reset --keep HEAD~2

This is it! The latest two commits have been removed from master and added to an existing branch.