8

Occasionally I find my self in the following situation: I am working on branch (say master) and I am editing some files, but when it comes the time for a commit I realize that I would prefer to commit to a new branch (say experimental). In other words, the old branch (master) must remain intact and a new branch should be created that will look like:

.. -- master -- new commit

What is the easiest way to do that?

Currently, I commit to old branch, then create the new branch and finally reset the old branch. But that's really ugly.

Mark Longair
  • 446,582
  • 72
  • 411
  • 327
tros443
  • 183
  • 4
  • 2
    possible duplicate of [Git: How to move existing work to new branch?](http://stackoverflow.com/questions/1394797/git-how-to-move-existing-work-to-new-branch) – brendan Oct 20 '11 at 05:03

3 Answers3

7
git checkout -b branch       # create new branch out of current head
git add <files>              # the changes you had done in your working directory will be carried over
git commit -m "message"      # commit!
manojlds
  • 290,304
  • 63
  • 469
  • 417
  • its mentioned in the question "but when it comes the time for a commit I realize that I would prefer to commit to a new branch" – COD3BOY Oct 20 '11 at 05:00
  • @user1004474 - Try it out. Both unstaged and stage changes will be there when you switch branch. – manojlds Oct 20 '11 at 05:03
  • 1
    Yes, you are right, I thought checkout would discard all changes. It's confusing, sometimes the same git command does different things. It would be nice I could do something like: git commit -b new_branch ....... – tros443 Oct 20 '11 at 05:10
  • 1
    well,I'm a beginner and I supposed that you should create a new branch before you make some changes! In this case user1004474 had already made the changes! So I was in a confusion. – COD3BOY Oct 20 '11 at 05:11
  • see, I had this same doubt as the user1004474! :D – COD3BOY Oct 20 '11 at 05:12
  • @user1004474 - That will not be the case because commits are not associated to branch, but to parent. There is plumbing commands that will allow you to create commits with particular parent that you want. – manojlds Oct 20 '11 at 05:13
1

It's slightly easier if you create the new branch first:

$ git checkout -b new_branch
$ git commit
hammar
  • 138,522
  • 17
  • 304
  • 385
  • The point is that I did not planned this ahead of time, so the changes were made first (and possible some of the added to the index with git add) and then I decide to branch. – tros443 Oct 20 '11 at 05:03
  • @user1004474: It still works. You can run a `git checkout -b new_branch` regardless of whether you have changes and whether they have been added to the index or not. – hammar Oct 20 '11 at 05:04
0

Another possibility is for you to go ahead and commit them to the master branch, then cut off another branch from the new HEAD (say feature). Once this is done, you can git reset master to the position before the commits.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169