How to git commit in a new branch after I've already made the changes?

7k views Asked by At

I understand that a command to start a new branch is

git checkout -b <mybranch>

However, that assumes I had the foresight to have created the new branch before making the new changes that I want to commit.

Usually however that's not the case. Usually, I start coding, then may or may not do git add . then want to commit in a new branch. How do I do that?

3

There are 3 answers

2
tpeters0 On

Go ahead and create the new branch, which essentially 'saves' what is on your current branch to the new branch.

Switch back to the previous branch and 'undo' your recent actions to restore that first branch to where you wanted it to be if you started the new branch at an ideal place.

(If it's only a few things - command z, or maybe go back to the prior commit, or re-pull from the last version on Github.) Then git add and commit that first branch, and you can switch back to the second to continue working.

Maybe not ideal, but I've used it as a work-around.

0
Nick Volynkin On

What's important here: Git branches do not contain any files or revisions by themselves. A branch is just a pointer to some commit. When you create a new branch, it takes the commit to point at from the current branch. Both will always (well, almost always) share common history, but may diverge after creation.

Branches bring in some utility features:

  • You can checkout a branch by its name (but you can also checkout a commit by its sha1, and in many other ways)
  • Say, a branch points to commit A. When you run git commit in that branch, a new commit B is created, which points to A. And the branch now points to B, the new recent commit.
  • Branches make it easier to visualize development paths and treat them as abstract objects.
  • Branches make it easier to merge revisions. (While it's also possible to merge raw commits).

To understand them better, I recommend you this course, which I'd taken myself. (Shame on me for recommending tutorials on SO. :)

3
Makoto On

Do it anwyay:

git checkout -b <new_branch>

What you'll see is something that looks like this:

git checkout -b new_branch
M   <changed_file>
Switched to a new branch 'new_branch'

You haven't committed anything into Git; with git add, you've only moved the files into staging. You can still create a new branch with your staged work. Any changes that aren't staged yet will have the opportunity to become staged on the new branch.