How to Commit Changes to a Git Branch
- Move Commits to a New Branch in Git
- Move Commits to an Existing Synchronized Branch in Git
- Move Commits to an Existing Branch in Git
This tutorial will see how to save commits to a new or existing branch in Git.
The article covers how to move commits to:
- A new branch
- 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.
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