How to Commit Current Changes to a Different Branch in Git

John Wachira Feb 15, 2024
How to Commit Current Changes to a Different Branch in Git

This article illustrates committing changes to a different branch in Git. When testing or trying out new things, we usually create a branch rather than committing dirty code to the master branch.

What if you find yourself with dirty code while still checked out in the master branch? How do you go about committing these changes to a different branch?

Commit Current Changes to a Different Branch in Git

The situation above is common and can be rather frustrating. If you find yourself in such a situation, follow these steps.

For easier context, we will use an example.

Assuming we have made some code changes in our master branch for testing purposes, how do we commit these changes to a testing branch in our repository?

Assuming these are the changes, how do we proceed?

changes to commit

We will need to use the git stash command to commit these changes to the testing branch. But before that, makes sure you commit the changes relevant to the master branch.

This helps resolve conflicts once we pop the stash in the other branch.

If you do not have any changes relevant to the master branch, you can proceed to run the git stash command.

$ git stash

This command will store the changes and remove them from your index. We can now switch to the testing branch.

$ git checkout testing

We can run the git stash pop command to drop the stash and bring the changes to the index of our testing branch.

$ git stash pop

stash pop

We can now add and commit the changes. You might encounter conflicts and have to manually resolve them to your liking.

It’s advisable to employ the help of a third-party mergetool like Meld. It makes it easier to identify and resolve conflicts.

Add the changes:

$ git add .

Commit the changes to our testing branch.

$ git commit -m "Test Code"

In a nutshell, the git stash command comes in handy when you want to commit your current changes to a different branch.

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.


Related Article - Git Commit