gitmergecommit

Merging 2 branches together in Git


I've only just started to use Git and think it is wonderful, however I'm a little confused over what the merge command does.

Let us say we have a working project in the branch "A".

I go home and make changes to this branch and save it as "B". Another programmer makes changes to "A" and saves it as "C".

Is there a way to merge the two branches "B" and "C" together, then commit the changes as a new branch, say "D"?

Or am missing the point of 'merge'?


Solution

  • merge is used to bring two (or more) branches together.

    A little example:

    $ # on branch A:
    $ # create new branch B
    $ git checkout -b B
    $ # edit files
    $ git commit -am "commit on branch B"
    
    $ # create new branch C from A
    $ git checkout -b C A
    $ # edit files
    $ git commit -am "commit on branch C"
    
    $ # go back to branch A
    $ git checkout A
    $ # edit files
    $ git commit -am "commit on branch A"
    

    So now there are three separate branches (namely A, B, and C) with different heads.

    To get the changes from B and C back to A, check out A (already done in this example) and then use the merge command:

    $ # create an octopus merge
    $ git merge B C
    

    Your history will then look something like this:

    …-o-o-x-------A
          |\     /|
          | B---/ |
           \     /
            C---/
    

    Alternatively, to create "regular" merge commits (with exactly two parents each), run git merge twice for each branch that you want to merge:

    $ git merge B
    $ git merge C
    

    To get a history similar to:

    …-o-o-x-------M-A
          |\     / /
          | B---/ /
           \     /
            C---/
    

    If you want to merge across repository/computer borders, have a look at git pull command, e.g. from the PC with branch A (this example will create two new commits):

    $ # pull branch B
    $ git pull ssh://host/… B
    $ # pull branch C
    $ git pull ssh://host/… C