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 bran
If you run into this issue and you have Visual Studio, you can do the following:
Right-click on your branch and select View History
:
Right-click on commit you want to go back to. And Revert or Reset as needed.
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 git reset --hard
will kill any untracked and modified changes you might have, so if you have those you might prefer:
git reset HEAD^
git checkout .
So if your scenario is that you've committed to master
but meant to commit to another-branch
(which may or not may not already exist) but you haven't pushed yet, this is pretty easy to fix.
// if your branch doesn't exist, then add the -b argument
git checkout -b another-branch
git branch --force master origin/master
Now all your commits to master
will be on another-branch
.
Sourced with love from: http://haacked.com/archive/2015/06/29/git-migrate/
4 years late on the topic, but this might be helpful to someone.
If you forgot to create a new branch before committing and committed all on master, no matter how many commits you did, the following approach is easier:
git stash # skip if all changes are committed
git branch my_feature
git reset --hard origin/master
git checkout my_feature
git stash pop # skip if all changes were committed
Now you have your master branch equals to origin/master
and all new commits are on my_feature
. Note that my_feature
is a local branch, not a remote one.
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.
To elaborate on this answer, in case you have multiple commits to move from, e.g. develop
to new_branch
:
git checkout develop # You're probably there already
git reflog # Find LAST_GOOD, FIRST_NEW, LAST_NEW hashes
git checkout new_branch
git cherry-pick FIRST_NEW^..LAST_NEW # ^.. includes FIRST_NEW
git reflog # Confirm that your commits are safely home in their new branch!
git checkout develop
git reset --hard LAST_GOOD # develop is now back where it started