Git - Moving Commits To Another Branch

There were a few occasions where I create git commits in the wrong branch and had to figure out how to move them to the right branch. So I am publishing this post as a reminder to myself, and hopefully it's useful to you.

Move Commit To New Branch

When I get too carried away writing code, I sometimes forget to create a feature branch and instead add commits to develop or master branch. In that scenario, I want to move the commit to a new branch. 



$ git branch new_branch
$ git reset --hard HEAD~1
$ git checkout new_branch




When you first create new_branch, the latest commit(s) will be in this branch. Then move HEAD a few commits back, and the newer commits will still be in new_branch

Move Commit To Existing Branch

But what if I want to move the new commits to an existing branch instead? In that case, I will need to merge or rebase the new commits before moving HEAD back in the original branch. 



$ git checkout wwdc
$ git merge master
$ git checkout master
$ git reset --hard HEAD~2




Here's a slide deck with visualisation and further explanation. 








No comments:

Post a Comment