Skip to main content

Merging branches in Git

Let's say you've been making commits in a branch (e.g. signup_web), and you've left master alone.

Now you want to bring your changes back into the master branch so that other developers in your team will know that you're done and they can use these changes in their code.

The solution is frenquently to merge your branch into master.

How to merge two branches

To do this you:

  • Activate the master branch;
  • Tell Git to get each commit from your branch, and apply the changes of each into the code in master.

The first step is easy:

git checkout master

The second step sounds hard, but it's also easy:

git merge signup_web

What if someone else made commits in master?

It can happen. While you're busy working in signup_web, someone else comes and makes some commits in the master branch.

They might commit directly to master (usually discouraged), or maybe they've merged their own branch into master before you merged yours.

So let's say that the repository commits look like this:

Merging diverging branches

No problem. Do the same as before:

git checkout master
git merge signup_web

It'll end up looking like this:

Diverging branches merged successfully

However, if both you and the other developer made changes to the same lines in the same files, you're going to encounter a merge conflict.

That's when Git gets confused because two commits changed the same file at same time, and it doesn't know which one to pick...

More information on merge conflicts and how to resolve them, in the next chapter!