How to Move the Recent Commits to New or Existing Branch

In this tutorial, you will learn how to move the latest commits to another branch, not changing the original branch.

Moving to an Existing Branch

Moving to the existing branch is useful when you have been working out of a feature branch, but all of a sudden started making commits in the wrong branch.

Here, the current branch with the commits needed to be removed is master.

Check out the existing branch with the git checkout command:

git checkout feature/existingbranch

Invoke the git merge command to bring the commits into the master. Running this will add the additional commits:

git merge master

Next check out the master branch:

git checkout master

Move the current branch back by two commits with the git reset command:

git reset --keep HEAD~2

The --keep option preserves the uncommitted changes in unrelated files, or aborts if the changes would have to be overwritten. If it aborts, git stash your changes and retry, or you can use the --hard option to lose the changes even from files that didn't change between the commits.

Moving to a New Branch

Moving to a new branch works by creating a new branch but not switching to it. Then you go back to the current branch (master) and switch to the new branch. Follow the steps to move your recent commits to a new branch.

Create a new branch which contains all current commits with the git branch command:

git branch feature/newbranch

Move the current branch back by two commits:

git reset --keep HEAD~2

Alternatively, instead of HEAD~2, you can add the hash of the commit you want to revert back like this:

git reset --keep a1b2c3d4

So, your two recent commits have been moved from master to a new branch.

The git reset and git checkout Commands

At first sight, the git reset and git checkout commands have some similarities since they both operate on HEAD. If git checkout operates exclusively on the HEAD reference pointer, git reset passes the HEAD reference pointer and the current branch reference pointer.

One of the most commonly used options of git reset is --hard. With --hard, the commit history reference pointers start pointing to the stated commit. After, the staging area and the working directory are reset to correspond to the stated commit. Changes that have been previously pending to the staging area and the working directory, are reset to match the commit tree state. Any pending commit in the staging index and working directory will be lost.

The --keep option resets index entries and updates files in the working tree that are different between commit and HEAD. When a file is different between commit and HEAD has local changes, reset is aborted.


Do you find this helpful?

Related articles