Satya's blog - git branches and git add -p

Oct 18 2014 07:26 git branches and git add -p

So you made some changes and want to commit to two different branches?

You have this:

$ git status

modified: foo
modified: bar

You want foo on branch A and bar on branch B. Easy enough:

$ git co A
$ git add foo
$ git commit
$ git co B
$ git add bar
$ git commit

You want foo on branch A along with one of your changes from bar. You want the other changes in file bar on branch B.

$ git co A
$ git add foo
$ git add -p bar
$ git commit
$ git co B
$ git add bar
$ git commit

Note the "git add -p bar". At that point, git will ask you, interactively, which changes you want to include in the changeset.

What if branch B doesn't exist yet? Instead of simply doing 'git co B' you would do 'git co -b B'.

At some point, you have a local branch that has never been pushed to the origin (that's just the usual name for the primary remote repo, btw). You can push the branch like this:

$ git push origin B

That pushes the current branch to a branch named B on origin. You could be on branch B, and do this:

$ git push origin C

And you've just pushed to a branch named C, and confused your future self.

Suppose you want to set up the remote branch and the local branch should track it. So that git status will show you things like "Your branch is ahead of origin/B by 10 commits [ you should push]" and also so that you can, in future, simply run `git push`. Then you'd do this on the first push:

$ git push -u origin B

And subsequent pushes would just be:

$ git push

Tag: howto git