Skip to main content

Git Branches

Git allows us to keep unrelated changes separate through the use of branches.

Git repositories start off with a single branch, called master.

Usually when a piece of software reaches a milestone and the code will be shared with users, it is the master branch code that is shared.

As such, the master branch frequently contains all the finished features and fixes of a project, such that at any time you could package it up and deliver it to your users.

Other branches often contain new features, bugfixes, or improvements to code in the master branch.

For example, if you're thinking of adding a new feature to your program, you could put it in a separate branch so that only changes related to this new feature are there.

That means that other collaborators who want to work in the repository don't need to see your "work in progress". They can create their own branches for their own work.

::: tip Keep the master branch clean and tidy of WIP for other collaborators. Create branches for your work as necessary. :::

When you've finished writing your new feature in your new branch, you should of course bring those changes into the master branch! That is called merging.

After merging your branch into the master branch, you'll want to delete your branch so that only the master branch remains. This helps keep the repository clean and free of old branches with old commits.

How to create a new branch

For this example:

  1. We've made 3 commits in the master branch.
  2. We've created a new branch with the git branch command.
  3. We've not committed on the new branch yet.

This is the command used to create the new branch:

git branch signup_web

What happens when we do that is that Git creates a branch label that points to the current commit, with the name signup_web.

Two branches on the same commit

Note that the latest commit here has two branch labels: master and signup_web. The * marks which branch we've got selected: the branch on which new commits will be made.

There's actually a third label on the current commit called HEAD. This label is always on the commit you're on at any given point in time. That's because in Git we can jump to another commit, so this is how Git keeps track of where we are right now. More on that later on!

Remember that each commit remembers the parent commit, so if we were to create a new commit in the signup_web branch, it would look like this:

One branch ahead

Notice that the master branch is still at C3 because we committed in signup_web. But if we go back to the master branch and commit there, the branches would now diverge:

  • master would get C5; and
  • signup_web would not (and still be on C4).

As shown here:

Diverging branches