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:
This changes master. It deletes the last 3 commits, and resets the index and working files:
Or: To stop the reset if there are changed working files that would get destroyed by --hard, then use --keep instead:
This makes my-branch the current branch, so you can work on it:
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:
This merges the master into my-branch, bringing all its commits:
This makes master the current branch again:
This changes master. It deletes the last 4 commits, and resets the index and working files:
Or: To stop the reset if there are changed working files that would get destroyed by --hard, then use --keep instead:
This switches you back to my-branch to admire the results:
If you want the simplest and easiest solution to this problem though, why not
try our Git client.