tags:

views:

237

answers:

3

D'oh! I just made a perfectly good commit to the wrong branch. How do I undo the last commit in my master branch and then take those same changes and get them into my upgrade branch?

Thanks!

+6  A: 

To rollback one commit (make sure you note the commit's hash for the next step):

git reset --hard HEAD^

To pull that commit into a different branch:

git checkout other-branch
git cherry-pick COMMIT-HASH

Also note that reset --hard will kill any untracked changes you might have, so if you have those you might prefer:

git reset HEAD^
git checkout .
Michael Mrozek
also, this is the bible for anything git: http://progit.org/book/
Ben
`git rev-parse BRANCH_NAME` to get the sha.
wilhelmtell
If you forget to note the hash first, just use `git reflog show <branch>`!
Jefromi
A: 

If you haven't yet pushed your changes, you can also do a soft reset:

git reset --soft HEAD^

This will revert the commit, but put the committed changes back into your index. Assuming the branches are relatively up-to-date with regard to each other, git will let you do a checkout into the other branch, whereupon you can simply commit:

git checkout branch
git commit

The disadvantage is that you need to re-enter your commit message.

Blair Holloway
+3  A: 

If you already pushed your changes, you will need to force your next push after resetting the HEAD.

git reset --hard HEAD^
git merge COMMIT_SHA1
git push --force

Just in case, on Windows(using Windows cmd line, not bash) it's actually four ^^^^ instead of one, so it's

git reset --hard HEAD^^^^
Igor Zevaka
Note that you should *not* force-push to a branch that other people are using unless absolutely necessary - otherwise they will be unable to push until they rebase. If you're the sole developer using git, however, this is fine.
Blair Holloway