The Wayback Machine - https://web.archive.org/web/20240927174643/https://www.geeksforgeeks.org/how-to-move-the-most-recent-commits-to-a-new-branch-with-git/
Open In App

How to Move the Most Recent Commit(s) to a New Branch With Git?

Last Updated : 31 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Git offers powerful features for managing your codebase efficiently. Sometimes, you may find yourself needing to move the most recent commit(s) to a new branch in Git. This could be due to various reasons, such as realizing that changes were made on the wrong branch or wanting to isolate experimental work. Fortunately, Git provides simple ways to accomplish this task. In this article, we’ll explore how to move the most recent commit(s) to a new branch with Git.

Why Move Commits to a New Branch?

Before diving into the steps, let’s briefly discuss why you might want to move commits to a new branch:

  1. Correcting Mistakes: You may have accidentally committed changes to the wrong branch and need to move them to the correct one.
  2. Isolating Changes: You might start working on a feature and realize it’s better suited as a separate branch for better organization and testing.
  3. Collaborative Workflow: Moving commits can help maintain a clean and organized workflow, especially in collaborative environments where each branch represents a specific task or feature.

Some terminological commands to do the task:

  • HEAD: Head pointer is the pointer that points to the most recent commit, which is reflected in the working tree. It stands for the currently checked out commit we’re working on.
  • git commit -m <message>: The current contents or changes in the repository are recorded through git committing. After git add  command, all the updated files reach the staging area, after which git commit fetch the changes to the repository with the commit message.
  • git branch <branch>: This command creates a new branch. This branch is nothing but a pointer to the snapshot of our changes from our main repository.
  • Relative references: Specifying commits by their hashes is a tedious job. So we use relative commits. One of them is ^ which means moving upwards one commit and ~<num> means moving upwards a number of times.
  • git hard reset to head: The purpose of the ‘git reset’ command is to move the current head to the commit specified. The –hard  option is used in order to reset the files of the index or the staging area and the changes in those files are lost, thus untracking them.
  • git checkout <branch>: The Git checkout command lets us navigate between the branches created by git branch. Checking out a branch updates the files in the working directory to match the version stored in that branch.

Steps to Move Recent Commits to a New Branch

Step 1: Check Current Status

Before making any changes, it’s a good practice to check the current status of your repository. Open your terminal or command prompt and navigate to the repository where you want to move the commits. Use the following command to view the current status:

git status

Step 2: Create a New Branch

Next, create a new branch where you want to move the recent commit(s). Use the following command to create a new branch and switch to it:

git checkout -b new-branch-name

Replace new-branch-name with the desired name for your new branch.

Step 3: Move the Commits

Now, let’s move the most recent commit(s) to the newly created branch. There are a couple of ways to achieve this, depending on whether you want to move just the most recent commit or multiple recent commits.

Moving the Most Recent Commit

If you only need to move the most recent commit, you can use the git reset command. Switch back to the original branch:

git checkout original-branch-name

Then, use the following command to reset the original branch to the previous commit, effectively removing the latest commit from this branch:

git reset --hard HEAD~1

Now, switch back to the new branch:

git checkout new-branch-name

And cherry-pick the removed commit onto the new branch:

git cherry-pick original-branch-name

Moving Multiple Recent Commits

If you need to move more than one recent commit, you can adjust the reset command to match the number of commits. For example, to move the last three commits:

git checkout original-branch-name
git reset --hard HEAD~3
git checkout new-branch-name
git cherry-pick original-branch-name..HEAD@{1}

In this command, HEAD~3 indicates the last three commits, and HEAD@{1} refers to the state of the branch before the reset.

Step 4: Verify Changes

After moving the commits, it’s essential to verify that everything is in order. Use the git log command on both branches to ensure the commits have been moved correctly:

git log

Check the log for both the original and new branches to confirm the commits are where they should be.



Similar Reads

How to Get List of Git Branches, Ordered By Most Recent Commit?
Git is a widely used version control system that helps manage code changes across different branches. Sometimes, you may need to see a list of branches sorted by the most recent commit. This can be useful for understanding the current state of development and prioritizing which branches need attention. This article will guide you through the steps
3 min read
How To Move Tag On a Git Branch To Different Commit?
Git is a powerful version control system that allows you to manage and track changes in your codebase. One useful feature of Git is tagging, which allows you to mark specific points in your project's history as important. Sometimes, you might need to move a tag from one commit to another, perhaps due to an error or an update in the code. This artic
2 min read
How to Move Existing, Uncommitted Work to a New Branch in Git?
Git is a widely used distributed version control and source code management system. A common scenario developers face is needing to move their uncommitted work to a new branch. This can be important for maintaining organized workflows, especially when realizing that ongoing changes belong to a separate feature or bug fix. In this article, we will s
2 min read
How To Move Branch Pointer To Different Commit Without Checkout?
Git pros frequently utilize this strong approach to rebase branches, correct errors, and modify branch histories: shifting the branch pointer to a different commit without checking out. With this approach, you can modify the commit that a branch points to without affecting the status of your working directory. When you need to make corrections to t
1 min read
How to Restore a Deleted Branch or Commit with Git?
Deleting a branch or a commit in Git might seem like a disaster, especially if it was done unintentionally. However, Git provides robust tools to help you recover deleted branches or commits. Here’s a detailed guide on how to restore a deleted branch or commit in Git. Table of Content Understanding the BasicsRestoring a Deleted BranchRestoring a De
3 min read
How to Create Branch From a Previous Commit Using Git?
Creating a branch from a previous commit in Git is a common task that allows developers to revisit and build on a specific point in their project's history. This can be useful for bug fixes, new feature development, or exploring alternate project paths without affecting the current state of the project. In this article, we will explore methods to c
2 min read
Git - Create a Branch From Another Branch
Branching in Git allows developers to work on isolated features or fixes without affecting the main codebase. However, what if you need to create a new branch based on the changes in another branch? That's where the concept of branching from another branch comes into play. In this guide, we'll see the process of creating a branch from another branc
3 min read
How to Make an Existing Git Branch Track a Remote Branch?
Managing branches in Git can sometimes be confusing, especially when you need to make an existing local branch track a remote branch. This process ensures that your local branch can easily fetch updates from and push changes to the corresponding remote branch. In this article, we will walk through the steps to set up tracking for an existing Git br
3 min read
How to Compare a Local Git Branch with its Remote Branch ?
When working with Git, it's often necessary to compare your local branch with its remote counterpart to understand the differences in terms of commits and changes. This helps in keeping your local work in sync with the remote repository and managing potential conflicts. This article will guide you through various methods to compare a local Git bran
3 min read
How to Make the Current Git Branch a Master Branch?
Managing branches effectively is a key part of using Git for version control. Occasionally, you might find yourself in a situation where the current branch you're working on should be the new master branch. This could be due to the current branch evolving to become the main line of development, or simply a restructuring of your project's branch str
3 min read
How to Replace Master Branch with Another Branch in GIT?
In Git, the "master" branch traditionally serves as the primary development branch in many repositories. However, there are situations where you might want to replace the contents of the "master" branch with those of another branch. This could be due to a variety of reasons, such as renaming the default branch to something more inclusive or reflect
2 min read
How to Create a Branch In Git from Another Branch?
Branching is a fundamental aspect of version control systems like Git, which helps developers work on multiple features or bug fixes simultaneously without interfering with the main codebase. Creating a branch from another branch is a common practice, especially when you want to build upon existing work or isolate changes for a specific feature. In
3 min read
Git Merge Hotfix Branch Into Feature Branch
When working on a software project, you may encounter situations where a hotfix needs to be applied to a feature branch. A hotfix typically addresses urgent issues in the codebase that need immediate attention and correction. Integrating these changes into a feature branch ensures that the fixes are incorporated into ongoing development, maintainin
4 min read
How To Replace Local Branch With Remote Branch in Git?
Managing branches in Git can sometimes require drastic measures, such as replacing a local branch entirely with its remote counterpart. This can be useful in scenarios where the local branch has diverged too much from the remote branch, leading to complexities that are easier to resolve by completely overriding the local branch. This article will g
4 min read
How to Undo the Most Recent Local Commits in Git?
When working with Git, it's common to make mistakes or realize that recent commits need to be revised. Whether you've made an error in your code, committed sensitive information, or simply want to restructure your commits, knowing how to undo the most recent local commits is an essential skill. This guide will walk you through the process of undoin
3 min read
How To Find The Most Recent Common Ancestor of Two Branches in Git?
In software development, managing code changes through version control systems is crucial. Git, one of the most popular version control systems, allows developers to create branches for features, bug fixes, or experiments. These branches can diverge from the main codebase and evolve independently. Eventually, you may need to find the most recent co
3 min read
Difference Between "git commit" and "git push"?
Git commit and git push are two essential commands you'll use a lot when working with Git. even their frequent use together, they have different functions. In order to help you understand when and how to use these two commands effectively in your version control workflow, this article will break down their differences. What is git commit?git commit
2 min read
How to Change the Commit Author for a Single Commit?
Changing the author of a single commit in Git can be done using an interactive rebase. This process involves rewriting the commit history, so it's important to proceed carefully, especially if you've already shared the commits with others. Here’s a step-by-step guide on how to change the commit author for a single commit Table of Content Steps to C
3 min read
How to Amend a Commit Without Changing Commit Message?
The git commit --amend command is used to modify the most recent commit. By default, this command opens the commit message editor, allowing you to update the commit message. However, you can amend the commit without changing its message, which can be particularly useful when you need to include forgotten changes or correct a mistake. Table of Conte
2 min read
How to Create a New Branch in Git and Push the Code?
Branching in Git is a helpful feature for software developers working on a big team project. It allows the team members to work on different aspects of the software by creating a branch from the main branch. The main branch is not affected by the changes in the created branch until it is merged into the main branch. Once, work is complete for the b
8 min read
How to Create a New Branch in Git?
Git is a powerful and widely used version control system that helps developers manage code changes across projects efficiently. One of the fundamental features of Git is branching, which allows developers to diverge from the main line of development and work on different tasks or features independently. This guide will walk you through the process
4 min read
How To Publish A New Branch In Git?
Git is a distributed version control system, offering powerful tools for collaboration, version tracking, and branching. One of its key features is branching, which allows developers to work on different features or fixes simultaneously without interfering with the main codebase. This article will guide you through the process of publishing a new b
4 min read
How To Find Out Which Remote Branch A Local Branch Is Tracking?
Git is a powerful version control system that allows developers to manage and track changes in their code repositories. One of the key features of Git is its ability to track relationships between local and remote branches. Knowing which remote branch a local branch is tracking can help you manage your workflow more efficiently, especially when col
3 min read
Difference Between Git remote prune, Git prune and Git fetch --prune
Git is a version control system that helps developers manage and track changes in their codebase. Among its many commands, git remote prune, git prune, and git fetch --prune are essential for maintaining a clean and organized repository. This article will explain the differences between these commands, their syntax, uses, and provide examples to il
4 min read
Git - Filtering the Commit History
Git source code versioning tool provides a lot of features. One of the most important and useful features is log or history. We can use git log command in order to list, filter, view commit history in different ways. Here we will examine git log command usage in detail with examples. List Commit History: We will start with git log command without a
4 min read
How To Revert A Commit With Git Revert?
Git is a distributed version control system that tracks changes in any set of computer files, usually used for coordinating work among programmers who are collaboratively developing source code during software development. It is free, open-source, and used by almost 95% of developers across the world. There are many popular offerings of Git reposit
5 min read
How to Back Commit in Git?
In this article, we are covering how to undo commits in Git. Sometimes, you might make mistakes or realize you need to revert changes you made in a previous commit. Luckily, Git offers a few ways to undo commits. Table of Content Approach 1: Using 'git revert'Approach 2: Using 'git reset' Approach 1: Using 'git revert''git revert' is the generally
4 min read
How to Delete Local Commit in Git?
Deleting a local commit in Git can be done in a few ways, depending on whether the commit is the most recent one or if it is further back in the commit history. Here’s an article on how to delete a local commit in Git, tailored to whether you want to keep the changes made in the commit or discard them entirely: Table of Content Keeping the Changes
3 min read
How to Change Commit Message in Git?
Changing a commit message in Git can be done in a few different ways, depending on whether the commit is the most recent one or an earlier commit. Here's an article on how to change a commit message in Git, covering scenarios both before and after the commit has been pushed to a remote repository.These are the following topics that we are going to
3 min read
How to Delete Commit in Git?
Deleting a commit in Git can be done in several ways, depending on whether the commit is local or has already been pushed to a remote repository. Here’s an article on how to delete a commit in Git, covering both recent and older commits, as well as considerations for working with remote repositories. Deleting the Most Recent CommitIf the commit onl
3 min read
Article Tags :