How to Commit Changes to Another Branch in Git

Published Mar 23, 2022  ∙  Updated May 2, 2022

How can we commit our current changes to another branch in Git?

Suppose we make changes in the working directory (i.e. branch1), but then we realize that the changes should be applied to another branch (i.e. branch2).

The solutions are different depending on whether we can switch branches.

If we cannot switch branches

If we can’t switch branches, we’ll get this message below when we try to checkout another branch.

Please commit your changes or stash them before you can switch branches.

We will get this message if any files are different between branch1 and branch2.

We can use git stash to “hide” our changes and create a temporary commit. Then, we will be able to checkout another branch.

Running git stash pop will re-apply this commit to the current branch.

git stash
git checkout branch2
git stash pop
git status
# git add + commit

If we can switch branches

If we can switch branches, we can simply checkout the other branch and commit normally.

git checkout branch2
git status
# git add + commit