Git: Oops! I Changed Those Files In The Wrong Branch!

I do this a lot… I’ll be assigned some work, start into it and get part way down the path, am ready for a commit and I realize that I’ve been changing code in the wrong branch of my local git repository. For example:


… but I didn’t want those changes on the master branch… I wanted them on some other branch, such as “mybranch” or “existingbranch”.

The good news is that git is AWESOME and this really isn’t a big deal. I can easily move these changes to a new branch or to an existing branch by doing one of the following… and there are probably many other ways of accomplishing the goal of moving your changes to a new or existing branch, too. These are the two methods I use most often, though.


Move To A New Branch

To move these changes to a new branch, run this command where “mybranch” is the name of the branch you want to create.

   1: git checkout -b mybranch

and then run git status again. You’ll see that the changes you made are still in place and you can now commit them to the new branch.



Move To An Existing Branch

To move these changes to an exiting branch, just checkout the other branch with the regular checkout command. For example, run this command where “existingbranch” is the name of an existing branch.

   1: git checkout existingbranch

Then run git status again, and you’ll see the same results but you’ll be on the existing branch:


About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs - the amazingly awesome podcast audio hosting service that everyone should be using, and where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in Branching Strategies, Git, Source Control. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • enriquein

    And that is why I can’t go back to bzr or Hg now. The way git does branching is pretty awesome (even if the commands aren’t intuitive and I have to tatoo a cheat sheet on my arm).

    Thanks for the tip.

  • Also useful if you need to want to change which branch you are working on, but need to do some merging/cleanup/etc on the target branch first:
    - git stash
    - change to the target branch and perform any steps to get it to the desired state
    - git stash pop

    Yep, git is awesome.

  • @josh,

    nice one! i haven’t played with stash very much… looks like another great tool i need to stick in my toolbox though. :)