threads / discuss / 8069

Switching branch before commit

Subject: Switching branch before commit

## tl;dr

3 messages between May 10, 2007 and May 10, 2007.

replies: 2people: 3as markdown or json

Ron Parker· May 10, 2007, 19:43 UTC · lore
I know this is probably a FAQ and I thought I found it somewhere once,
but... How do I commit changes from in my working directory to another
(possibly non-existent) branch?
 
All too often I am working on changes and realize I am sitting on master
or a topic branch and I need to commit my mods to different branch.  I
really don't like:
 
    git commit
    git branch <other-branch>
    git reset --hard HEAD^
 
Is there anything like:
    git commit -b <other-branch> [<file>...]?
If not, would patches to implement such a change be accepted?
Adam Roben· May 10, 2007, 20:02 UTC · re: Ron Parker · lore

Re: Switching branch before commit

On May 10, 2007, at 12:43 PM, Ron Parker wrote:
Show 17 quoted lines
> I know this is probably a FAQ and I thought I found it somewhere once,
> but... How do I commit changes from in my working directory to another
> (possibly non-existent) branch?
>
> All too often I am working on changes and realize I am sitting on  
> master
> or a topic branch and I need to commit my mods to different branch.  I
> really don't like:
>
>    git commit
>    git branch <other-branch>
>    git reset --hard HEAD^
>
> Is there anything like:
>    git commit -b <other-branch> [<file>...]?
>
> If not, would patches to implement such a change be accepted?
    You can do this simply by doing the following:

git checkout -b <other-branch> git commit

    The changes in your working tree will be carried over to <other- 
branch> when you do the git-checkout command.
-Adam
Junio C Hamano· May 10, 2007, 20:08 UTC · re: Ron Parker · lore

Re: Switching branch before commit

"Ron Parker" <ron.parker@mobot.org> writes:
Show 11 quoted lines
> I know this is probably a FAQ and I thought I found it somewhere once,
> but... How do I commit changes from in my working directory to another
> (possibly non-existent) branch?
>  
> All too often I am working on changes and realize I am sitting on master
> or a topic branch and I need to commit my mods to different branch.  I
> really don't like:
>  
>     git commit
>     git branch <other-branch>
>     git reset --hard HEAD^

I do not like that either, and I wouldn't do that. In fact that would not work, as "git branch" would not switch to the other branch you just created.

I would do:
	$ git checkout -b other-branch

which would create and switch to other-branch, based on the current HEAD (in your case, 'master'), WITHOUT disrupting what is in your working tree and the index.

and then (perhaps after working on it some more to perfection):
	$ git commit

to commit that work I (mistakenly) started on 'master' in that other branch. Then I would come back to master:

	$ git checkout master

← back to recent threads