I\'d like to move the last several commits I\'ve committed to master to a new branch and take master back to before those commits were made. Unfortunately, my Git-fu is not
The method exposed by sykora is the best option in this case. But sometimes is not the easiest and it's not a general method. For a general method use git cherry-pick:
To achieve what OP wants, its a 2-step process:
newbranch
Execute
git checkout master
git log
Note the hashes of (say 3) commits you want on newbranch
. Here I shall use:
C commit: 9aa1233
D commit: 453ac3d
E commit: 612ecb3
Note: You can use the first seven characters or the whole commit hash
newbranch
git checkout newbranch
git cherry-pick 612ecb3
git cherry-pick 453ac3d
git cherry-pick 9aa1233
git checkout newbranch
git cherry-pick 612ecb3~1..9aa1233
git cherry-pick applies those three commits to newbranch.
Here's a far simpler solution for commits to the wrong branch. Starting on branch master
that has three mistaken commits:
git reset HEAD~3
git stash
git checkout newbranch
git stash pop
master
master
, yet leaves all working files intactmaster
working tree exactly equal to the HEAD~3 statenewbranch
You can now use git add
and git commit
as you normally would. All new commits will be added to newbranch
.
The OP stated the goal was to "take master back to before those commits were made" without losing changes and this solution does that.
I do this at least once a week when I accidentally make new commits to master
instead of develop
. Usually I have only one commit to rollback in which case using git reset HEAD^
on line 1 is a simpler way to rollback just one commit.
Don't do this if you pushed master's changes upstream
Someone else may have pulled those changes. If you are only rewriting your local master there's no impact when it's pushed upstream, but pushing a rewritten history to collaborators can cause headaches.