Oscar the owl and Vershd logo

Git Move Commit to Another Branch

23rd March 2020

This is part of a Git Tips series. For the complete set for beginner and intermediate Git users, see our white paper.

The Problem

It's too early in the day, and the tea / coffee / taurine hasn’t kicked in yet. You’ve made some commits, and now realise they’re on entirely the wrong branch, master, to be exact. You can already hear the pedants in the office tutting.

You need to move these Git commits to another branch, either a new branch, or an existing one. Here’s how to do this.

The Solution for a New Branch

In this example, there are 3 commits to move.

This creates the new branch my-branch, containing all the commits:
git move commit to another branch
git branch my-branch
This changes master. It deletes the last 3 commits, and resets the index and working files:
git reset --hard HEAD~3
Or: To stop the reset if there are changed working files that would get destroyed by --hard, then use --keep instead:
git reset --keep HEAD~3
This makes my-branch the current branch, so you can work on it:
git checkout my-branch
Warning: If after doing this you need to rebase this new branch onto the master, you may need to use --no-fork-point to protect your moved commits, otherwise they might get erased.

The Solution for an Existing Branch

In this example, there are 4 commits to move.

This switches you to the branch you want the commits on, my-branch:
git checkout my-branch
This merges the master into my-branch, bringing all its commits:
git merge master
This makes master the current branch again:
git checkout master
This changes master. It deletes the last 4 commits, and resets the index and working files:
git reset --hard HEAD~4
Or: To stop the reset if there are changed working files that would get destroyed by --hard, then use --keep instead:
git reset --keep HEAD~4
This switches you back to my-branch to admire the results:
git checkout my-branch

The Quickest & Easiest Solution

Do you need a Git GUI that's totally free for personal use? Vershd boosts your software development productivity by making Git simple with a unique UI/UX. It's a Git GUI that prevents errors and creates clarity. This Git client soars over your repository and then swoops down to quickly tackle branches, commits and files. It deals with Git, so you can concentrate on coding.

Get screenshots and a 60 second video of what Vershd, the effortless Git GUI can do for you.
Oscar the owl and Vershd logo
 © 2020 Blightysoft
Made in England
St. George's flag of EnglandThe Union Jack, the flag of the United KingdomThe European Union flagThe United Nations flag
chevron-right linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram