How to Commit Changes to a Git Branch

John Wachira Feb 02, 2024
  1. Move Commits to a New Branch in Git
  2. Move Commits to an Existing Synchronized Branch in Git
  3. Move Commits to an Existing Branch in Git
How to Commit Changes to a Git Branch

This tutorial will see how to save commits to a new or existing branch in Git.

The article covers how to move commits to:

  1. A new branch
  2. An existing branch

You will often find yourself committing the same staged changes to different branches. Git allows you to conveniently do this, as shown below.

Move Commits to a New Branch in Git

This section will see how to move the commits in your workspace branch to a new branch.

Create a new branch that will contain all your commits. Use the git branch command to initialize a new branch.

git branch <new-branch>

The command above will create a branch, a new-branch.

Use the git reset command to reset commits to the last update.

git reset --keep HEAD~N

We use the --keep option to back up uncommitted changes.

Move Commits to an Existing Synchronized Branch in Git

To understand this feature better, we will use a practical example. We made commits to the <wrong branch> instead of the <right branch>.

Assuming the two are synchronized, how do you bring the commits to the <right branch>?

Navigate to the existing branch with the git checkout command.

git checkout <right branch>

Move the commits with the git merge command.

git merge <wrong branch>

To remove the mistaken commits, got to the <wrong branch>.

git checkout <wrong branch>

Use the git reset command to revert the commits.

git reset --keep HEAD~N

Move Commits to an Existing Branch in Git

Let us use a practical example to understand this better. How would you go about it if you want to move a specific commit without merging the branches?

We will move one commit from the <wrong branch> to the <right branch> in the example below.

Switch to the <right branch>.

git checkout <right branch>

Use the git cherry-pick command and the commit’s hash to move it, as shown below.

git cherry-pick <sha1-commit-hash>

Go back to the <wrong branch> and use the git reset command to remove the commit.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Branch