If you’ve followed along with the previous tutorials, you now know how to work with commits, stage files, view the commit log, and maybe a few other things.

Now it’s time to use one of git’s most useful features: branching.

What is a branch?

In reality, a branch is just a named pointer to a commit. But for most purposes, thinking of a branch like a branch of a tree is fine.

When you create a branch, it’s like creating a separate line of history, starting from the commit where it was created.

Later on, the branch can be merged into its parent branch (or any other branch for that matter).

Creating branches

Creating a branch is easy:

$ git branch <branch name>

Then switch to the new branch using:

$ git checkout <branch name>

Those steps can be combined into one command:

$ git checkout -b <branch name>

-b: create a new branch

Listing branches

To list branches in your repo, use the branch subcommand:

$ git branch

The branch prefixed with an asterisk (*) is the currently checked out branch.

The status subcommand also shows the current branch.

I’m not going to go through how to create commits on a different branch, since it’s the same as you would do normally.

Note: make sure you git checkout the branch you want to commit to.

Merging a branch

Let’s assume your main branch is called master and your secondary branch is called foo.

Once you have some commits on branch foo, merge it into master using these two commands:

$ git checkout master

$ git merge foo

Fixing merge conflicts

If the same file(s) were modified in both the master and foo branches, there may be merge conflicts, i.e. where the changes made affect each other, and must be manually resolved.

Git will tell you when this happens:

$ git merge foo

Auto-merging file.txt
CONFLICT (content): Merge conflict in file.txt
Automatic merge failed; fix conflicts and then commit the result.

The conflicting file will then look something like this:

<<<<<<< HEAD
>>>>>>> foo

The conflict markers (<<<<<<<, =======, >>>>>>>) show where the conflicts are. Resolve the changes, then stage the file.
Repeat this for every conflicting file. Run git commit to complete the merge.

Two-step merge

Adding the --squash option to the merge subcommand will cause git to make the changes necessary to merge, but not create the merge commit.

You can then review the changes, and run git commit to complete the merge.

Aborting the merge

If you perform a two-step merge, either with the --squash option, or because of conflicts, you can cancel it using:

$ git merge --abort