Open In App

How to move the most recent commit(s) to a new branch with Git

Git is a powerful tool in the modern software world. Chunks of files and code are stored in projects through git branching and committing. Branching allows developers to diverge from the production version of code to fix a bug or add a feature. Whereas when you create a commit, git identifies that snapshot of files with a unique SHA-1 hash. Branching on that commit will create a new pointer along with the master branch. Branches let us work on different versions of a project.

Moving the most recent commits to a new branch is necessary, as in the case if we want to fix a bug without changing the main version of the project. Also, if we want to implement a new feature without effecting the main project, we do git branching. For this, we will create a new branch to the recent commits along with the main branch. Then we move back to the state or commit we want this we do by resetting the master branch. A visual representation is given below.



First and foremost, we need to know some terminological commands to do the task:



Below are the steps to move the most recent commits to the new branch:

  1. First we create 4 commits to the existing repository with unique hashes named C0,C1,C2 and C3, the main branch as well as the head pointer moves along with committing. Now to move the recent, commits to a new branch we will create a new branch named scripter.
  2. git branch scripter command will create a new branch consisting all the code on the master branch. Now as we have created a new branch , we can move the master branch back by one commit or a number of commits as required.
  3. We can do this by git reset –hard HEAD^ and moving the head pointer by one after one commit, git reset –hard HEAD~n will move the master branch ‘n’ commits before the recent commit, and git reset –hard <sha1-commit-hash> will directly move the master branch to the desire commit. Alternatively, –keep instead of –hard preserves the uncommitted changes in unrelated files.
  4. Lastly, git checkout scripter is to checkout the newly formed branch with the version of our project that has recent commits.
Article Tags :
Git