Blog / Git branching after committing

Git branching after committing

18 Jul 2010, by James Kong

Let's say you make some changes on your master branch and commit a few times. So when you do a good old 'git status' you may have something like this ```bash kongy@Deadpool:~/Development/Sentia/project (master) $ git status # On branch master # Your branch is ahead of 'origin/master' by 3 commits. ``` However you now realize you have taken the red pill. You are in the middle of a monster feature, and realise that you should have branched before. Luckily we can fix this using some git magic. "Why, oh why, didn't I take the blue pill?" Let's go back 3 commits by checking it out. ```bash kongy@Deadpool:~/Development/Sentia/project (master) $ git checkout HEAD~3 Note: moving to 'HEAD~3' which isn't a local branch If you want to create a new branch from this checkout, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b HEAD is now at 978b493... Merge branch 'master' of github.com:Sentia/project ``` Nice! Now our repository is sitting pretty at 3 commits previously. And even better, git also tell us how to create a branch from this point. So let's do that now push the newly created branch up to Github. ```bash kongy@Deadpool:~/Development/Sentia/project ((no branch)) $ git checkout -b magic Switched to a new branch 'tiling' kongy@Deadpool:~/Development/Sentia/project (magic) $ git push origin magic Total 0 (delta 0), reused 0 (delta 0) To git@github.com:Sentia/project.git * [new branch] magic -> magic ``` Now that we have created and saved the branch, lets grab all those changes in master, merge them into our branch, and push up to Github ```bash kongy@Deadpool:~/Development/Sentia/project (magic) $ git merge master Updating 978b493..8a74bd3 Fast forward project.rb | 443 ++++++++++----------------------- ``` Cool, so our branch is now up to date. Now all we have to do is fix our master branch to become the same as the the GitHub origin master branch. I think there is probably an easier way to do this but I went and got the SHA commit key for the HEAD of origin to know where I wanted to go back to. ```bash kongy@Deadpool:~/Development/Sentia/project (magic) $ git checkout master Switched to branch 'master' Your branch is ahead of 'origin/master' by 3 commits. kongy@Deadpool:~/Development/Sentia/project (master) $ git reset --hard 978b493631a1443b1c84 HEAD is now at 978b493 Merge branch 'master' of github.com:Sentia/project ``` And you're done. Now you can work in peace on your branch without disturbing your fellow developers. And then cry when you need to merge their changes into your branch.