How to move a commit to another branch in Git

Kenny DuMez
Kenny DuMez
Graphite software engineer


Note

This guide explains this concept in vanilla Git. For Graphite documentation, see our CLI docs.


When working with Git, there might be times when you need to move commits from one branch to another. This guide will walk you through the process of moving commits using different methods such as git cherry-pick.

First, create the new branch (if it doesn't already exist) and switch to it:

Terminal
git checkout -b <new-branch>

Replace <new-branch> with the name of the branch you want to create and move your commit to.

Next, you can use git cherry-pick to apply the commit from the source branch to the target branch. If you're moving the last commit, you can run:

Terminal
git cherry-pick <commit-hash>

To get the commit hash of the last commit, run:

Terminal
git log -1

Copy the hash and use it in the cherry-pick command.

Switch back to the original branch:

Terminal
git checkout <source-branch>

Then, reset the branch to remove the last commit:

Terminal
git reset --hard HEAD~1

This command will reset the branch to the state before the last commit, effectively removing it.

Use git log to identify the commit hashes you want to move:

Terminal
git log

Create the new branch and switch to it:

Terminal
git checkout -b <new-branch>

Cherry-pick the commits one by one or use a range:

Terminal
git cherry-pick <commit-hash1> <commit-hash2> ...

Or for a range of commits:

Terminal
git cherry-pick <commit-hash1>^..<commit-hashN>

Switch back to the original branch:

Terminal
git checkout <source-branch>

Then, use interactive rebase to remove the specific commits:

Terminal
git rebase -i <commit-hash>^

In the interactive rebase screen, change the command for the commits you want to drop from pick to drop.

Another method to move commits is by using git rebase. This can be useful if you want to move a series of commits from one branch to another in a more automated fashion.

Create the new branch and switch to it:

Terminal
git checkout -b <new-branch>

Switch back to the source branch and rebase it onto the new branch:

Terminal
git checkout <source-branch>
git rebase <new-branch>

If you are working on a remote repository and need to update the branches, you may need to force push the changes:

Terminal
git push --force

Be cautious with force pushing as it can overwrite history.

For more information see this guide on cherry-picking in Git.

Git inspired
Graphite's CLI and VS Code extension make working with Git effortless.
Learn more

Graphite
Git stacked on GitHub

Stacked pull requests are easier to read, easier to write, and easier to manage.
Teams that stack ship better software, faster.

Or install our CLI.
Product Screenshot 1
Product Screenshot 2